如何检查是否存在相同的随机对象

时间:2019-03-28 18:02:38

标签: c#

我正在做简单的Xamarin.Forms益智游戏,我需要有9个具有不同随机值的谜题。 我试图通过一些循环检查它,但仍然无法正常工作。

Random r = new Random();

            Label[] puzzles = { puz1, puz2, puz3, puz4, puz5, puz6, puz7, puz8, puz9 };
            string[] used = new string[9];
            for (int i = 0; i < puzzles.Length; i++)
            {
                if (i > 0)
                {
                    for (int x = 1; x < used.Length; x++)
                    {
                        do
                        {
                            puzzles[i].Text = Puzzles.puz[r.Next(0, 8)];
                            used[x] = puzzles[i].Text;
                        }
                        while (used[x - 1] == used[x]);
                    }
                }
                else
                {
                    puzzles[i].Text = Puzzles.puz[r.Next(0, 8)];
                    used[0] = puzzles[i].Text;
                }
            }

和Puzzles.cs类

class Puzzles
    {
        public static string[] puz = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };


    }

如何检查新生成的拼图与以前生成的拼图的价值不一样?

2 个答案:

答案 0 :(得分:0)

这是因为您仅检查前面的值是否重复,使得used[x -2] == used[x]仍然可能为true。

为实现您的目标,我建议实现一个随机播放功能,就像您可以find here那样。它可以给出这样的东西

// Implemented somewhere in your code
private List<E> ShuffleList<E>(List<E> inputList)
{
     List<E> randomList = new List<E>();

     Random r = new Random();
     int randomIndex = 0;
     while (inputList.Count > 0)
     {
          randomIndex = r.Next(0, inputList.Count); //Choose a random object in the list
          randomList.Add(inputList[randomIndex]); //add it to the new, random list
          inputList.RemoveAt(randomIndex); //remove to avoid duplicates
     }

     return randomList; //return the new random list
}

// Then for each element of your puzzles array, you could do
puzzles[i].Text = SuffleList(Puzzles.puz);

答案 1 :(得分:0)

谢谢大家的帮助,我不知道Shuffle机制。最后,我的“工作”代码如下所示

        static Random rnd = new Random();

        static void Shuffle<T>(T[] array)
        {
            int n = array.Length;
            for (int i = 0; i < n; i++)
            {
                int r = i + rnd.Next(n - i);
                T t = array[r];
                array[r] = array[i];
                array[i] = t;
            }
        }

        public Game()
        {
            InitializeComponent();


            Label[] puzzles = { puz1, puz2, puz3, puz4, puz5, puz6, puz7, puz8, puz9 };

            string[] puz = { "1", "2", "3", "4", "5", "6", "7", "8" };

            Shuffle(puz);
            for (int i = 0; i < puzzles.Length - 1; i++)
            {
                puzzles[i].Text = puz[i];
            }
        }