vendredi 10 mars 2017

c# returning array from function gives same result when recalled

Got an issue which I think I know why is happening but want to make sure. 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.

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.

Aucun commentaire:

Enregistrer un commentaire