1

Got an issue where my code will generate numbers for the user and then generate numbers to compare against, although when I call this multiple times it always comes out with the same numbers even though it is supposed to be random for each call.

An example of my output is:

17,41,47,46,21,39,18

And when I call the function again I get the same output as above even though I call the function again which should produce new numbers

Menu options:

case 1:
    ticketNumbers = PlayerPickNumbers();
    CheckWinningTicket(ticketNumbers);
    break;
case 2:
    ticketNumbers = AIPickNumbers();
    CheckWinningTicket(ticketNumbers);
    break;

Random number method....

static int[] AIPickNumbers() 
    {
        int[] numbersPicked = new int[7]; // Digit 7 is bonus ball
        int randomPicked = 0;
        Random rnd;
        rnd = new Random();

        for (int i = 0; i < 7; i++)
        {

            randomPicked = rnd.Next(1, 50);

            while (numbersPicked.Contains(randomPicked) == false)
            {
                numbersPicked[i] = randomPicked;
            }

            Console.Write(randomPicked + ",");
        }
        Console.WriteLine();

        return numbersPicked;
    }

Winning Ticket method...

static void CheckWinningTicket(int[] userNumbers)
    {
        int[] winningNumbers = new int[7];
        winningNumbers = AIPickNumbers(); // Generate winning numbers to compare against
        int[] userPickedNumbers = new int[7];
        userPickedNumbers = userNumbers;

        int totalmatches = 0;

        totalmatches = winningNumbers.Intersect(userPickedNumbers).Count();

        Console.WriteLine("You had " + totalmatches + " match(es)");


    }

I think the issue is when random is createdit is being created too fast and as such will always return the same numbers but not 100% sure.

Robertgold
  • 215
  • 6
  • 19
  • 3
    [`Random`](https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx) is a PRNG (pseudorandom number generator), not a source of 'true' randomness. It's deterministic: the same internal state always produces the same 'random' number. That internal state is initialized with a seed value. If you don't specify a seed yourself, a time-dependent value is used - so if you create multiple `Random` instances in quick succession it's very likely that they will have the same internal state - and thus produce the same numbers. – Pieter Witvoet Mar 10 '17 at 09:36
  • So in short I need to do something such as: Random rnd = new Random(Guid.NewGuid().GetHashCode()); – Robertgold Mar 10 '17 at 09:39
  • 1
    Or just create a single `Random` instance and reuse it. – Pieter Witvoet Mar 10 '17 at 09:43

0 Answers0