## 2 replies

Last post Jan 05, 2011 04:40 PM by Andrew Morton

• Mr.JB

Member

18 Points

89 Posts

### Random() Class - Unique

I was looking for some assistance with the Random() Class.

What I'd like it to do, and maybe I don't understand its abilities, is generate random "positions" for a range of 1-10 Elements.  In my case, 10 Images, in a 5x3 Grid (15 possible spaces).  My application shows a Sample with 2 Comparisons, and on load, generates a random sample from a database.

For the sake of ease, I'll just mention the 'Sample'. There may be 1 to 10 images shown in the Sample Area.

If 10 images show, I need 10 random positions from 1 - 15.  This is how I have it written.  Seems to work, with the exception that some of the numbers duplicate.  Is that not a capability of the Random Class?

In Sum: If I need 10 Positions, they need to be random positions from 1 - 15, but not duplicating.  Is there an easier way to do this, or a way to 'exclude' the number once it has been hit?

```Dim cRandoms As New Random()
Dim cRandNumbers As Integer

Do While cNumberOfPositionsNeeded > 0
cRandNumbers = cRandoms.Next(1, 16)
If cRandNumbers = 1 Then
cP1 = True
cP1Count = cP1Count + 1
Else
If cRandNumbers = 2 Then
cP2 = True
cP2Count = cP2Count + 1
Else
If cRandNumbers = 3 Then
cP3 = True
cP3Count = cP3Count + 1
Else
If cRandNumbers = 4 Then
cP4 = True
cP4Count = cP4Count + 1
Else
If cRandNumbers = 5 Then
cP5 = True
cP5Count = cP5Count + 1
Else
If cRandNumbers = 6 Then
cP6 = True
cP6Count = cP6Count + 1
Else
If cRandNumbers = 7 Then
cP7 = True
cP7Count = cP7Count + 1
Else
If cRandNumbers = 8 Then
cP8 = True
cP8Count = cP8Count + 1
Else
If cRandNumbers = 9 Then
cP9 = True
cP9Count = cP9Count + 1
Else
If cRandNumbers = 10 Then
cP10 = True
cP10Count = cP10Count + 1
Else
If cRandNumbers = 11 Then
cP11 = True
cP11Count = cP11Count + 1
Else
If cRandNumbers = 12 Then
cP12 = True
cP12Count = cP12Count + 1
Else
If cRandNumbers = 13 Then
cP13 = True
cP13Count = cP13Count + 1
Else
If cRandNumbers = 14 Then
cP14 = True
cP14Count = cP14Count + 1
Else
If cRandNumbers = 15 Then
cP15 = True
cP15Count = cP15Count + 1

End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
cNumberOfPositionsNeeded = cNumberOfPositionsNeeded - 1
Loop```

---------- |--
I learned.
---------- |--
• Mr.JB

Member

18 Points

89 Posts

### Re: Random() Class - Unique

I came up with a long handed solution.  I sure wish I knew an easier way to format it, but as the story goes, running short on time ;-)

`End if`

This is the shortened version of 15 variable...

---------- |--
I learned.
---------- |--
• Andrew Morto...

Member

240 Points

59 Posts

### Re: Random() Class - Unique

Jan 05, 2011 04:40 PM|Andrew Morton|LINK

One way:

1. Make a list of the numbers you want to pick from.

2. Pick one out at random and remove it from the list.

3. Repeat step 2 for as many numbers as you need (or until the list is empty).

HTH,

Andrew