Android Question implementing random none reapeated integers

Addo

Well-Known Member
Licensed User
Longtime User
i am trying to generate a random none repeated integers

i do something like following

B4X:
Sub randnumbers(Upperange As Int) As Int
    
Dim d As Int
d = Rnd(0, Upperange)
Do While d < 1002
d = Rnd(0, Upperange)
Loop

Return d   
    
End Sub

is there a better approach to do a randomize integers ?
 

DonManfred

Expert
Licensed User
Longtime User
1. I dont see how you are preventring generating two identical integers!?
2.
Do While d < 1002
If you dont want values <1002 then you should directly use
B4X:
Dim d As Int
d = Rnd(1002, Upperange)
 
Last edited:
Upvote 0

LucaMs

Expert
Licensed User
Longtime User
The question is not clear enough.

B4X:
Dim s As B4XSet = B4XCollections.CreateSet
For i = 1 To 100
   s.Add(Rnd(1, 1000))
Next
For Each number As Int In s.AsList
   Log(number)
Next
Note that the set size might be smaller than 100.
Creates your code a list of non-repeated numbers?

I was already writing the following code:
B4X:
    Private lstNumbers As List
   lstNumbers.Initialize
   Dim UpperRange As Int = 1000
   Dim RandomNumber As Int = Rnd(1, UpperRange + 1)
   For i = 0 To 9
       Do Until lstNumbers.IndexOf(RandomNumber) = -1
           RandomNumber = Rnd(1, UpperRange + 1)
       Loop
       lstNumbers.Add(RandomNumber)
   Next
   lstNumbers.Sort(True)
   Log(lstNumbers) 'ignore
 
Upvote 0
Top