multiple for next loops

cadcamman

Member
Licensed User
Longtime User
Hi All

can someone point me in the right direction, I am writing a little lotto number picker and I want to check the random number generator doesn't select duplicate numbers I tried to do it with a nested for next loop but I couldn't do it. I eventually did it as follows but id doesn't look a good way

Thanks

For j = 0 To 5
temp = Rnd(1,50)
num(j) = temp
Log(num(j))
Next

For i = 0 To 4
If num(i) = num(i+1) Then
Msgbox("error","Error")
Return
End If

Next

For i = 1 To 4
If num(i) = num(i+1) Then
Msgbox("error","Error")
Return
End If

Next

For i = 2 To 4
If num(i) = num(i+1) Then
Msgbox("error","Error")
Return
End If

Next

For i = 3 To 4
If num(i) = num(i+1) Then
Msgbox("error","Error")
Return
End If

Next

End Sub
 

stevel05

Expert
Licensed User
Longtime User
The easiest way is to keep track of the numbers already picked in an array, and select again if it chooses a duplicate, something like:

B4X:
Dim Results(51) As Boolean
Dim Num(6) As Int
For i = 0 To 5
   temp=Rnd(1,50)
   If Results(temp) = True Then Continue  ' send it back to pick that one again
   Results(temp)=True
   Num(i)=temp
Next

'Show the results
For i = 0 To 5
   Log(Num(i))
Next
 
Last edited:
Upvote 0

stevel05

Expert
Licensed User
Longtime User
No Problem, this one is better, uses a different loop I didn't test the other one properly.

B4X:
Dim Results(51) As Boolean
Dim Num(6) As Int
Dim Temp As Int

Dim i As Int =0
Do While i < 6
   Temp=Rnd(1,50)
   Log("T ="&Temp)
   If Results(Temp) = True Then Continue  ' send it back to pick that one again

   Results(Temp)=True
   Num(i)=Temp
   i=i+1
Loop

For i = 0 To 5
   Log(Num(i))
Next
 
Upvote 0

cadcamman

Member
Licensed User
Longtime User
Hi Stevel

the first one worked fine except it chose zero as one of the numbers, which is strange because the random number generator was set between 1 and 50

doesn't this mean it should only select numbers between 1 and 49

thanks
 
Upvote 0

stevel05

Expert
Licensed User
Longtime User
The problem was when it found a duplicate, it recorded zero. Yes it should be 1-49. The new code should work correctly.
 
Upvote 0
Top