0

I tried the following code to generate random numbers and store them in a HashSet in c#:

class program
{
  static void Main(String[] args)
  {
    Random r=new Random();
    HashSet <int> h = new HashSet<int>();
    for (int j=0;j<9;++j)
    {
  h.Add(r.Next(9));
    }
    int [] array = h.ToArray();
    foreach(int i in array)
  Console.WriteLine(i);
    Console.ReadLine();
   }
}

Each time I execute the program, the number of elements being displayed differs. Since I'm using a loop to store 9 values, I expect 9 values to be displayed, which is not happening. What could be the possible error?

Raul Guiu
  • 2,374
  • 22
  • 37
Awani
  • 394
  • 3
  • 7
  • 19

1 Answers1

1

HashSet doesn't contain duplicates.Your loop runs 9 times but only unique numbers are added to the HashSet.Add your numbers directly to your array and you should see 9 numbers displaying. Or use a wider range to generate random numbers.Btw you can verify that how many numbers in the HashSet like this, after the for loop:

Console.WriteLine(h.Count);

Alternatively you can change your for loop like this:

for (int j = 0; j < 9; ++j)
{
    if(!h.Add(r.Next(9))) j--;
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • We could use an array, but it is displaying the numbers in an order. I want to generate numbers in random order everytime. How do I do that? – Awani Mar 22 '14 at 13:30
  • @user2195963 you can create an ordered array then shuffle it.See this question: http://stackoverflow.com/questions/273313/randomize-a-listt-in-c-sharp – Selman Genç Mar 22 '14 at 13:33
  • Thanks, the code worked. Could you please explain the if statement you have used? – Awani Mar 22 '14 at 13:39