Peter
Peter

Reputation: 857

Java - Generate a random -1 or 1?

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

Answers (6)

krassib
krassib

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

Bozho
Bozho

Reputation: 597046

how about:

random.nextBoolean() ? 1 : -1;

where random is an instance of java.util.Random

Upvotes: 33

jwl
jwl

Reputation: 10514

return Math.floor(Math.random()*2)*2-1;

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

How about

Random r = new Random();
n = r.nextInt(2) * 2 - 1;

Upvotes: 0

Peter Alexander
Peter Alexander

Reputation: 54270

return Random.nextInt(2) * 2 - 1;

Upvotes: 2

JustinKSU
JustinKSU

Reputation: 4989

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

Upvotes: 0

Related Questions