Android Question Rnd problem/question

alienware40

Member
Licensed User
Longtime User
Hi,

I have sort of a problem when using rnd function.

Rnd(0, 10) will get me any random number between 0 and 9, but can I somehow exclude for example number 7?

Thanks a lot,
Leon.
 

mangojack

Expert
Licensed User
Longtime User
there might be a more elegant way .. but for a simple fix ..

B4X:
Dim rndNum As Int
     rndNum  = Rnd(1, 10)  ' Create random number. 1 to 9

   Do While rndNum = 7     ' Do not accept #7
     rndNum = Rnd(1, 10)
  Loop

  Log (rndNum)
 
Last edited:
Upvote 0

Straker

Active Member
Licensed User
Longtime User
Hi,

I have sort of a problem when using rnd function.

Rnd(0, 10) will get me any random number between 0 and 9, but can I somehow exclude for example number 7?

Thanks a lot,
Leon.

B4X:
    Dim x As Int
    x=7
    Do Until x<>7
        x=Rnd(0,10)       
    Loop

Unfortunately B4A doesn't have a DO / LOOP UNTIL construct.
If someone knows a better way to write this code, it will be appreciate.
 
Upvote 0

mc73

Well-Known Member
Licensed User
Longtime User
B4X:
x=Rnd(0,9)
if x > 6 then x = x+1

No, no, no. That would give 7 a twice as high probability as the other outcomes.
Why? From what I see in Derez's code, we have 9 outcomes (0->8) with equal probability. Adding 1 when >6, just transposes in order to avoid 7.
 
Upvote 0
Top