-1

I am trying to generate a random number when I click a button. But when I do I will get the same numbers at times. When I click the button it also will hide a label. When I click on buttons there should be no labels left. Image

private static Random rnd = new Random();
randomNumber = rnd.Next(0, 25);

How can I prevent it from using the same number more then once until the program is closed/restarted?

  • 3
    Random numbers are random. It's entirely possible that if you ask for a random number five times, one will repeat. If you're restricting them to only appearing once, they're no longer random. What exactly are you trying to do? – Ken White May 27 '17 at 02:38
  • @Ken-White When I click a button I want it to choose a label at random. I have saw that its possible to generate a random number from an array then prevent it from being chosen again by checking if it was previously used. I just don't know how to do it all the way. – TitanBuilder1 May 27 '17 at 02:48
  • 2
    And what I'm asking is why you're wanting a random number when you want it not to be random. If you ask 10 people to pick a number between 1 and 10, chances are quite good that more than one of them will pick the same number; that's random. If you want it not to be random, then populate an array, pick choices from the array and mark them as used, and reject numbers that aren't available, but don't call them random numbers. They're a range of numbers that are restricted to single use, but in no way *random*. – Ken White May 27 '17 at 02:55
  • @Ken-White the number that is applied to each object will be different. for example you run it once and 5 buttons get numbers in the order 2-3-1-4-5 run it again and you get 4-3-2-5-1 etc. Then I will have those numbers reference labels. I just need to know how to prevent buttons getting assigned numbers like 5-2-4-2-3 etc. where 2 is applied twice I don't want that. – TitanBuilder1 May 27 '17 at 03:04
  • And I described exactly how to do that in my last comment. What part don't you understand? – Ken White May 27 '17 at 03:05
  • 1
    You don't want random numbers. You want a pre-determined set of numbers, selected in random order. See marked duplicate for how to do that. – Peter Duniho May 27 '17 at 03:07

1 Answers1

0

By definition, if you do what you want, the number generated would stop being random.

So, as what you want to get any duplicates, you should take a list of the numbers in the interval you've chosen, shuffle them, and then grab one at a time.

An efficient way to do this is the one described in here. This uses the Fisher-Yates algorithm to shuffle what in your case will be ints.

Juan T
  • 1,219
  • 1
  • 10
  • 21