1

I am trying to save random numbers in a list, the same number can not come twice. It´s a BINGO game where this method is used to display ex B12, then the user hits enter and a new number will show. This will keep on until the user writes q.

This works, BUT the number can show up twice...

static void bingo()
{
    Random rnd =new Random();
    List<int> check = new List<int>();
    string choice = "";

    while (choice != "Q")
    {
        int number = rnd.Next(1, 76);

        while (!check.Contains(number))
        { 
            kontroll.Add(number); 
        }
        if (number <=15)
        {
            choice = Interaction.InputBox("B" + number);
            choice = choice.ToUpper();
        }
        else if(number <= 30)

        etc.
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
user3356636
  • 115
  • 1
  • 11
  • 6
    so generate a list of all possible letters/numbers first and then shuffle that list and then iterate through the list. you'll never get a repeat as long as you keep moving "forward" in the list. – Marc B Mar 18 '14 at 20:15
  • possible duplicate of [Randomize a List in C#](http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp) – Alexei Levenkov Mar 18 '14 at 20:27

3 Answers3

2

Something like this should work (if I'm reading your question correctly)

Enumerable.Range(1,76).OrderBy(n => rnd.NextDouble())

Kelly Robins
  • 7,168
  • 6
  • 43
  • 66
0

There are a couple of ways to do this:

  1. Keep track of what numbers have been "called" - if a number is in the list, pick a different one
  2. Remove numbers that have been called from the original list, then pick a new one at random each time.
  3. Sort the list of possible values by a random number and just work though the list
D Stanley
  • 149,601
  • 11
  • 178
  • 240
-1

The easiest way to accomplish this is to use a HashSet.

var usedNumbers = new HashSet<int>();
...
int number;
do {
    number = rnd.Next(1, 76);
} while (usedNumbers.Contains(number));
usedNumbers.Add(number); 
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188