2

How do I store a random number into my array, but only if there is not a duplicate already inside the array? My code below still inputs a duplicate number.

        Random rand = new Random();
        int[] lotto = new int [6];

        for (int i = 0; i < lotto.Length; i++)
        {
            int temp = rand.Next(1, 10);
            while (!(lotto.Contains(temp)))//While my lotto array doesn't contain a duplicate
            {
                lotto[i] = rand.Next(1, 10);//Add a new number into the array
            }
            Console.WriteLine(lotto[i]+1);
        }
bsd u
  • 77
  • 1
  • 6

2 Answers2

4

Try this:

Random rand = new Random();
int[] lotto = new int[6];

for (int i = 0; i < lotto.Length; i++)
{
    int temp = rand.Next(1, 10);

    // Loop until array doesn't contain temp
    while (lotto.Contains(temp))
    {
        temp = rand.Next(1, 10);
    }

    lotto[i] = temp;
    Console.WriteLine(lotto[i] + 1);
}

This way the code keeps generating a number until it finds one that isn't in the array, assigns it and moves on.

There are a lot of ways to 'shuffle' an array, but hopefully this clears up the issue you were having with your code.

RagtimeWilly
  • 5,265
  • 3
  • 25
  • 41
1

What you really want is to shuffle the numbers from 1 to 9 (at least that's what your example is implying) and then take the first 6 elements. Checking for duplicates is adding unnecessary indeterminism and really is not needed if you have a shuffle.

E.g take this accepted answer for a Fisher-Yates shuffle and then take the first 6 elements for lotto.

This would then look like this:

lotto = Enumerable.Range(1,9)
                  .Shuffle()
                  .Take(6)
                  .ToArray();
Community
  • 1
  • 1
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335