Awani
Awani

Reputation: 394

Generating and storing unique and random numbers within a range

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?

Upvotes: 0

Views: 264

Answers (1)

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

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--;
}

Upvotes: 1

Related Questions