Reputation: 857
Does anyone have a quick way to randomly return either 1 or -1?
Something like this probably works, but seems less than ideal:
return Random.nextDouble() > .5 ? 1 : -1;
Upvotes: 6
Views: 6389
Reputation: 66
import java.util.Random;
public class RandomTest {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
System.out.println(randomOneOrMinusOne());
}
}
static int randomOneOrMinusOne() {
Random rand = new Random();
if (rand.nextBoolean()) return 1;
else return -1;
}
}
Upvotes: 0
Reputation: 597046
how about:
random.nextBoolean() ? 1 : -1;
where random
is an instance of java.util.Random
Upvotes: 33