The next code snippet, return a list with non repeating random numbers
Feel free to modify or use it as you want.
This code depends on JavaObject and Inline Java Code usage.
I decide to use the inline java because the Core random function (RND) get stuck at some point, I do not have the Core random function code to compare with my code, but a similar situation happened when I took off the number 1 in my inline java code.
The next code is an addition of my original post as an example of how to use it
The output should be
Enjoyed!!
Feel free to modify or use it as you want.
This code depends on JavaObject and Inline Java Code usage.
I decide to use the inline java because the Core random function (RND) get stuck at some point, I do not have the Core random function code to compare with my code, but a similar situation happened when I took off the number 1 in my inline java code.
B4X:
random.nextInt((max - min) + 1) + min;
B4X:
'Return As List : A list with random numbers
'lSize As Int : Number of elements to return in the list
'rnNub As Int : Number minimum for the random range
'rnMax As Int : Number maximum for the random range
'Code Example:<code>
' Dim listOfRndNumbers As List
' listOfRndNumbers.initialize
' 'Next line return a List with 10 items with random numbers where the minimum is 20 and the maximum is 777
' listOfRndNumbers=GetRndNonRepeatingList(10,20,777)
' For Each n As Int In listOfRndNumbers
' Log(n)
' Next</code>
'This Sub depends on JavaObject
Sub GetRndNonRepeatingList(lSize As Int, rnMin As Int, rnMax As Int) As List
Dim llist As List
Dim nr As Int
llist.Initialize
Private nNativeMe As JavaObject
'nNativeMe.InitializeContext
If rnMax+1>=lSize And rnMin<rnMax Then
Do While llist.Size< lSize
nr=nNativeMe.RunMethod("GetRndJAVAInt", Array(rnMin,rnMax))
If llist.IndexOf(nr)=-1 Then
llist.Add(nr)
End If
Loop
End If
Return llist
End Sub
#If JAVA
import java.util.Random;
public static int GetRndJAVAInt(int min, int max) {
Random random = new Random();
return random.nextInt((max - min) + 1) + min;
}
#End If
The next code is an addition of my original post as an example of how to use it
B4X:
Dim lSize As Int = 3
Dim nrMin As Int = 0
Dim nrMax As Int = 2
Dim llist As List = GetRndNonRepeatingList(lSize, nrMin, nrMax)
llist.Sort(True)
For Each n As Int In llist
Log(n)
Next
The output should be
B4X:
0
1
2
Enjoyed!!
Last edited: