# I am trying to populate an array with 9 random numbers but having some problems.

• ### Question

• User1602108015 posted

The first problem I am having is that it populates every cell with the same random number.  How do I get it to create a new random number?  The second problem is that I need to make sure each entry in the array is unique.

Here's my code.  Does anyone see the problem?

Dim UsedCards(5) As Integer
Dim intRandomNumber As Integer
Dim X As Integer

DealCards()
End Sub

Sub DealCards()
UsedCards(0) = GetRandomNumber(1, 52)
UsedCards(1) = GetRandomNumber(1, 52)
UsedCards(2) = GetRandomNumber(1, 52)
UsedCards(3) = GetRandomNumber(1, 52)
UsedCards(4) = GetRandomNumber(1, 52)
End Sub

Function GetRandomNumber(ByVal intLowLimit As Integer, ByVal intHighLimit As Integer)
Dim RandomGenerator As Random
Dim intRandomNumber As Integer
RandomGenerator = New Random()
intRandomNumber = RandomGenerator.Next(intLowLimit, intHighLimit)
GetRandomNumber = intRandomNumber
End Function

Tuesday, November 9, 2010 2:04 PM

• User1224194097 posted

Check if the number exists in the list and add. Otherwise continue the loop until the array count reaches 5 or 9 or your desired count

Try this

` Dim UsedCards As New List(Of Integer)        Dim rand As New Random()        While UsedCards.Count <= 5            Dim randomNumber = rand.Next(1, 52)            If Not UsedCards.Contains(randomNumber) Then                UsedCards.Add(randomNumber)            End If        End While`

• Marked as answer by Thursday, October 7, 2021 12:00 AM
Tuesday, November 9, 2010 2:26 PM

### All replies

• User1224194097 posted

Check if the number exists in the list and add. Otherwise continue the loop until the array count reaches 5 or 9 or your desired count

Try this

` Dim UsedCards As New List(Of Integer)        Dim rand As New Random()        While UsedCards.Count <= 5            Dim randomNumber = rand.Next(1, 52)            If Not UsedCards.Contains(randomNumber) Then                UsedCards.Add(randomNumber)            End If        End While`

• Marked as answer by Thursday, October 7, 2021 12:00 AM
Tuesday, November 9, 2010 2:26 PM
• User1602108015 posted

Would I use a for loop to check the values in the array in order to make sure the new number isn't already in the array?

If so, I can figure out how to do that.  However, I can't figure out how to choose a new random number if it is already used, but move forward if it's not, while still staying in the loop.

I can do an IF statement that chooses a new random number if the number is already used, but I can't figure out how to check that number as well.

Tuesday, November 9, 2010 2:37 PM
• User1224194097 posted

Suppose if you want to insert random numbers into an array of length 5.

Use a

While(array.Length<=5)

{

//Check if number exists

//add the number if not exists

}

That loop continues until your array gets filled with 5 unique random numbers.

Tuesday, November 9, 2010 3:53 PM