B4J Code Snippet Return Rnd number in step mode

Erel

B4X founder
Staff member
Licensed User
Longtime User
Another implementation:
B4X:
'Returns a random number between Min (inclusive) Max (exclusive!) Step (Stp number)
Sub RndStep(Minimum As Int, Maximum As Int, Stp As Int) As Int
   Dim i As Int = Rnd(Minimum, Maximum)
   i = i - ((i - Minimum) mod Stp)
   Return i   
End Sub

Your code can be problematic. It will be very slow if the possible range of numbers is large (time and space complexity of O(n) where n is the range, my solution complexity is O(1)).
 

ilan

Expert
Licensed User
Longtime User
Ok this is smart @Erel :)

EDIT: but wrong :p

Log(RndStep(5,20,2))

when i get number 8 then

i = i - ((i - Minimum) mod Stp)

i = 8 - ((8-5) mod 2) = 7

return 7

and 7 is not an even number!
 
Last edited:

ilan

Expert
Licensed User
Longtime User
maybe thats the solution:

B4X:
'Returns a random number between Min (inclusive) Max (exclusive!) Step (Stp number)
Sub RndStep(Minimum As Int, Maximum As Int, Stp As Int) As Int
   Dim i As Int = Rnd(Minimum, Maximum)
   i = i - (i mod Stp)
   If i < Minimum Then i = i + Stp
   Return i 
End Sub
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
and 7 is not an even number!
It is based on your implementation. It starts from the minimum and adds the step multiple times. So 7 is a valid number.

If you want to start the series of allowed numbers from 0 instead of the minimum:
B4X:
'Returns a random number between Min (inclusive) Max (exclusive!) Step (Stp number)
Sub RndStep(Minimum As Int, Maximum As Int, Stp As Int) As Int
   If Minimum Mod Stp <> 0 Then Minimum = (Floor(Minimum / Stp) + 1) * Stp
   Dim i As Int = Rnd(Minimum, Maximum)
   i = i - (i mod Stp)
   Return i  
End Sub
 

ilan

Expert
Licensed User
Longtime User
It is based on your implementation. It starts from the minimum and adds the step multiple times. So 7 is a valid number.

you are right my code was wrong i wanted to get only a number in the range between min and max that divides by step
 
Last edited:
Top