6

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;
Peter
  • 837
  • 3
  • 14
  • 19

6 Answers6

33

how about:

random.nextBoolean() ? 1 : -1;

where random is an instance of java.util.Random

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • +1 Because this is the simplest of all the answers (some are really clever). However, just want to add that it is likely that *the same Random instance* should generally be used instead of always creating a new one ... otherwise leads to interesting "duplicate values" in degenerate situations. –  Jun 14 '11 at 18:14
  • @pst agreed on that. I just wanted to fit it on one line. I'll remove the instantiation. – Bozho Jun 14 '11 at 18:17
  • 1
    Warning: you don't want to code this line inside a loop, it would not work! A single random object should be created outside. – leonbloy Jun 14 '11 at 18:17
  • @leonbloy just addressed that. The example was simplified, now it's more complete. – Bozho Jun 14 '11 at 18:17
  • Just remember that `java.util.Random` class generates poor quality random numbers. It is suitable only for "casual" use. – Jarek Przygódzki Jun 14 '11 at 18:43
  • "poor quality" is relative. For most typical uses it's ok. For critical applications, it's not. http://stackoverflow.com/questions/453479/how-good-is-java-util-random/ – leonbloy Jun 14 '11 at 19:06
2
return Random.nextInt(2) * 2 - 1;
Peter Alexander
  • 53,344
  • 14
  • 119
  • 168
  • 2
    @JustinKSU: No it wouldn't. The `nextInt` produces 0 or 1, which doubles to 0 or 2, which then becomes -1 or 1. The `nextInt` value is exclusive. – Peter Alexander Jun 14 '11 at 18:12
0

new Random.nextInt(2) == 0 ? -1 : 1;

JustinKSU
  • 4,875
  • 2
  • 29
  • 51
  • nextInt(integer) is between 0 (inclusively) and int (exclusively). thus you need Random.nextInt(2) – iliaden Jun 14 '11 at 18:13
0

How about

Random r = new Random();
n = r.nextInt(2) * 2 - 1;
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
0
return Math.floor(Math.random()*2)*2-1;
jwl
  • 10,268
  • 14
  • 53
  • 91
0
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;
}

}

krassib
  • 66
  • 4