首页 > 解决方案 > 如何检查是否存在相同的随机对象

问题描述

我正在做简单的 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" };


    }

如何检查新生成的谜题与之前生成的谜题的值不同?

标签: c#

解决方案


这是因为您只检查前面的值是否有重复项,仍然有可能为used[x -2] == used[x]真。

为了实现您的目标,我建议您实现一个 shuffle 功能,就像您可以在此处找到的那样。它可以给出这样的东西

// 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);

推荐阅读