簡體   English   中英

如何檢查是否存在相同的 Random 對象

[英]How to check there is the same Random object

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


    }

如何檢查新生成的拼圖與之前生成的拼圖的值不同?

這是因為您只檢查前面的值是否有重復,這使得used[x -2] == used[x]仍然可能為真。

為了實現您的目標,我建議您實現一個隨機播放功能,就像您可以在這里找到的那​​樣 它可以給出這樣的東西

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

感謝大家的幫助,我不知道 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];
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM