I would do:
int possibilities = 7;
int x = ThreadLocalRandom.current().nextInt(possibilities);
int y = ThreadLocalRandom.current().nextInt(possibilities - 1);
if (y >= x)
y++; // adding 1 to y here means that y can't equal x
This way y
is equally likely to be any of the integers in the range 0
to possibilities - 1
except x
.
ThreadLocalRandom.current().nextInt(possibilities);
is just an alternative way of generating a random number in a range. ThreadLocalRandom.current()
just gives an instance of the Random
class, and nextInt
is a method for producing random numbers in a range (I prefer this to the Math.random
approach).
However, you may find it easier to understand this solution, which is more similar to your original question.
int possibilities = 7;
int x = (int) (Math.random() * possibilities);
int y = (int) (Math.random() * (possibilities - 1));
if (y >= x)
y++;