0

Random numbers

I'm trying to generate 2 random numbers x1 and x2 between 0 and 10 using the Math.random() method. How do I make sure that x1 >= x2 at all times?

26th Sep 2020, 8:43 AM
Ndeji Chiputa
Ndeji Chiputa - avatar
3 odpowiedzi
+ 3
Math.random() creates a double between 0 and 1 (but 1 is not included). So you will probably want to multiply this by 10 (and maybe round it or convert to int). One way is that after generating both numbers, you check their values, and just swap them if not appropriate. If you have to keep them in the same order, then you can generate the first value, then just make a loop to generate the second number until it meets your condition.
26th Sep 2020, 8:58 AM
Tibor Santa
Tibor Santa - avatar
+ 3
You can making condition to controll that for example if x1 < x2 : x1 = reassign x to new number that is not less than x2
26th Sep 2020, 8:59 AM
HBhZ_C
HBhZ_C - avatar
+ 2
double x2 = Math.random() * 10; double x1 = Math.random() * (10 - x2) + x2; That'll do the trick. No loop, if-statement, or swapping is required. I recommend keeping it as simple as possible like I've done with the above 2 lines.
26th Sep 2020, 9:09 AM
Josh Greig
Josh Greig - avatar