how to dont Repetition Random number

dev4you

Member
hi
i have question how can i Random numbers with out Repetition
i use this code and its show this error in Emluter

java.lang.arrayindexoutofboundsexception


B4X:
Dim x() as Boolean

i= rnd(1,20)
if x(i) = false then
'conition1
Else
x(i) = false
end if
now that I tried other codes such as

B4X:
Dim x() as string

i= rnd(1,20)
if x(i) = "false" then
'conition1
Else
x(i) = "false"
end if
and still the same problem
 

LineCutter

Active Member
Licensed User
If you're trying to do what I think you're trying to do they you're not generating random numbers so much as shuffling cards (20 of them).

There is basic4PPC code here that will show you how to do that.

Oh also, x() doesn't look like it's been initialised so you can test for "false" in the original code.
 

dev4you

Member
Erel thank you
but i'm beginner i dont understand this example
can you put to me simple example code to Generates number from 1-10
and dosent Repeat any number
thanks Again
 

Erel

Administrator
Staff member
Licensed User
Here:
B4X:
Sub Activity_Create (FirstTime As Boolean)
   Dim numbers(10) As Int
   'put numbers 1 - 10 in the array
   For i = 0 To 9
      numbers(i) = i + 1
   Next
   ShuffleArray(numbers)
   For i = 0 To 9
      Log(numbers(i)) 'print the numbers to the log
   Next
End Sub

Sub ShuffleArray(arr() As Int)
   For i = arr.Length - 1 To 0 Step -1
      Dim j, k As Int
      j = Rnd(0, i + 1)
      k = arr(j)
      arr(j) = arr(i)
      arr(i) = k
   Next
End Sub
Based on this algorithm: Fisher–Yates shuffle - Wikipedia, the free encyclopedia
 

dev4you

Member
Erel
thanks for you :sign0148:

but :sign0013: can you write to me the full code that
i want when i click on button1 that generate random number "whit out repeat" in label1

thank you very much Erel :sign0085:
 

timo

Active Member
Licensed User
x Dev4you:

B4X:
Sub Button1_Click
'(put the code directly in the button)

Dim numbers(10) As Int
'put numbers 1 - 10 in the array
For i = 0 To 9
numbers(i) = i + 1
Next
ShuffleArray(numbers)
For i = 0 To 9
Log(numbers(i)) 'print the numbers to the log
Next

'goes here:
Label1.Text=numbers(0)
Label2.Text=numbers(1)
Label3.Text=numbers(2)
'....
'etc

End Sub

Sub ShuffleArray(arr() As Int)
For i = arr.Length - 1 To 0 Step -1
Dim j, k As Int
j = Rnd(0, i + 1)
k = arr(j)
arr(j) = arr(i)
arr(i) = k
Next
End Sub
 
Last edited:
Top