I have 3 variables, A, B and C, and randomly assign them 3 possible numbers, 1,2 or 3 Want to assign. An equals b can be, but C can not be equal either, so if a = 2 and = 1, then c = 3. If a = 1 and b = 1, then c or 2 or 3 (randomly ) should be there.
Currently I do: a and b = random value then:
if (a == b) {do {c = (int) (Math.Random) () * 3); } While (C == A); } Else {do {c = (int) (Math.random () * 3); } While (c == a || c == B); }
Is this the best way? How do I do this?
(1) Calling to generate a random number is the most expensive thing you are doing here So, you should reduce it as much as possible (two or three times).
(2) You probably want java.util.Random
, especially if you want int
s.
java.util.Random random = new java.util.Random (); Int a = random.nextInt (3) + 1; Int b = random.nextInt (3) + 1; Int c = 0; For (int n = a == b? Random.nextInt (2): 0; n> = 0; n--) {to {c ++; } While (c == a || c == B); }
This will be "equally" random.
Explanation:
We first of all like a
and b
For either c
is left with one or two options, even if it is a
equals b
. We "roll the dice" for c
and find the place where fits in c
.
Comments
Post a Comment