-1

I was making a kind of poker game where you play against an ai and you both get an array of random numbers. When creating the method for it, I noticed that the program always created the same array for both.

public short[] GenerateNumbers(short[] playerNumbers)  //The generate numbers method creates an array of random numbers
        {
            Random randNumb = new Random();  //Creation of a random type object called randNumb. This object is the one that creates the random numbers in the array

            playerNumbers = new short[5];  //Stating the length of the player's array

            for (int i = 0; i < playerNumbers.Length; i++)  //This loop creates random numbers for every position in the array
            {
                playerNumbers[i] = (short)randNumb.Next(1, 9);
            }

            playerOneHand = playerNumbers;

            return playerOneHand;
        }

        public short[] GenerateAINumbers(short[] aiNumbers)  //The generate numbers method creates an array of random numbers
        {
            Random randAINumb = new Random();  //Creation of a random type object called randNumb. This object is the one that creates the random numbers in the array

            aiNumbers = new short[5];  //Stating the length of the player's array

            for (int j = 0; j < aiNumbers.Length; j++)  //This loop creates random numbers for every position in the array
            {
                aiNumbers[j] = (short)randAINumb.Next(1, 9);
            }

            aiHand = aiNumbers;

            return aiHand;
        }
Franz Gleichmann
  • 3,420
  • 4
  • 20
  • 30
  • 3
    Does this answer your question? [Random.Next returns always the same values](https://stackoverflow.com/questions/1654887/random-next-returns-always-the-same-values) (search term used: `c# random creates same results`) – Franz Gleichmann May 18 '21 at 10:44
  • 1
    Do read up [MSDN](https://learn.microsoft.com/en-us/dotnet/api/system.random.-ctor?view=net-5.0#System_Random__ctor_System_Int32_) before posting here! – TaW May 18 '21 at 11:18

1 Answers1

0

You can create an instance level Random object:

private Random rnd = new Random();

public short[] GenerateNumbers(short[] playerNumbers) {...}

public short[] GenerateAINumbers(short[] aiNumbers) {...}

You can use this rnd object in your methods instead of creating always a new one.

Kapitany
  • 1,319
  • 1
  • 6
  • 10