Unique, Random Number Generator

ShiftySid

Member
Joined
Mar 7, 2005
Messages
15
Programming Experience
3-5
Hi,

I am trying to create code to display ten UNIQUE numbers between 0 and 10 in some text boxes.

I can get it to display random numbers in the text boxes, but I have duplicate numbers. Does anyone know how I can code it, so that duplicates are eliminated?

My form consists of ten text boxes, and a command button. The code (so far) is as follows:

VB.NET:
Private Sub btnClick_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnClick.Click
 
Dim r As New System.Random
Dim n(9) As Integer
Dim i As Integer
 
For i = 0 To 9
n(i) = r.Next(0, 11)
 
Next
 
txt0.Text = n(0)
txt1.Text = n(1)
txt2.Text = n(2)
txt3.Text = n(3)
txt4.Text = n(4)
txt5.Text = n(5)
txt6.Text = n(6)
txt7.Text = n(7)
txt8.Text = n(8)
txt9.Text = n(9)
 
End Sub
Many thanks!

Shifty.
 
I suggest you generate the number and check against all retained numbers. If it already exists, then reject it and move on to the next till all slots are filled.

Happy programming.
 
like this...

VB.NET:
Dim r As New System.Random
Dim n(9) As Integer
Dim i As Integer
 dim current as integer
For i = 0 To 9
current = r.next(0,11)
if array.indexof(n,current)= -1
n(i) = current
else
i-=1 'not sure about this bit here. i would [U]hope[/U] that this doesnt ensure blank elemnts in your array 
      'if the current variable is already existing in the array.
end if
 
Next

hope it helps :)
adam

edit: after reading this again, i realise this is probably the long winded way of doing it, so someone will probably suggest something even better soon, but just in case, enjoy! :)
 
Back
Top