1

I'm trying to create a random number generator between 1 and 500 that does not repeat itself. I made an array to keep track of if a generated number has been used but it doesn't seem to be working

if (drawnTF[num] == false)
            {
                labels[labelNum].Visible = false;
                txtLatestDrawnNum.Text = "Latest Drawn Number: " + latestDrawnNum.ToString("000");
                drawnTF[num] = true;
            }
            else
            {
                while (drawnTF[num] == true)
                {
                    num = random.Next(0, 499);
                    if (drawnTF[num] == false)
                    {
                        labelNum = 499 - num;
                        labels[labelNum].Visible = false;
                        txtLatestDrawnNum.Text = "Latest Drawn Number: " + latestDrawnNum.ToString("000");
                        drawnTF[num] = true;
                    }
                }
            }
  • 2
    So, you want to randomly shuffle the order of the numbers 1,2,3,...,500. Look around here on StackOverflow. There are plenty of C# questions with answers about exactly that problem/task... –  May 25 '19 at 17:39
  • Possible duplicates: https://stackoverflow.com/questions/375351/most-efficient-way-to-randomly-sort-shuffle-a-list-of-integers-in-c-sharp, https://stackoverflow.com/questions/273313/randomize-a-listt, https://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm (Man, the search function here on StackOverflow rocks! Hard!) –  May 25 '19 at 17:40
  • Not sure what you are trying to do with those labels, but when you find an unextracted number you should exit from that loop with a _break_ – Steve May 25 '19 at 17:42
  • Depending on your requirements regarding the distribution of the pseudo random numbers, you could have various approaches. One simple solution if you are not to concerned about the distributions, is to use a bunch of different parameters to make up the number. Example: Look at the current ram usage, the time in milliseconds, the keyboard hit rate past 10 key strokes and the wifi signal, then scale for whatever range you want. – jkazan May 25 '19 at 17:44
  • Wouldnt _drawnTF[num] = true;_ be breaking the loop naturally? @Steve – zukuto hughes May 25 '19 at 17:45
  • 1
    If that expression could break the loop then how do you enter the loop? – Steve May 25 '19 at 17:46
  • Possible duplicate of [Randomize a List](https://stackoverflow.com/questions/273313/randomize-a-listt) – Simply Ged May 25 '19 at 22:41

1 Answers1

5

You can try to put 500 numbers in an list and do a next(0,values.Length). Each time you pick a random number you remove it from that list. This way you will always have different numbers.

Sergiu
  • 130
  • 6