views:

579

answers:

3

Hi- I need a function that will return a random integer that can be only -1, 0, or 1. Thanks?

+8  A: 

How about generating a random from 0 to 2 and subtracting 1?

Apocalisp
Genius!!!!!!11!
Tom Hawtin - tackline
Thought about submitting an Enterprise solution, but it's proprietary.
Apocalisp
Ya, thanks..............
Why not generate a random number from 17 to 19 and subtract 18?
Bombe
@Bombe, you've opened the door to a very dark place. Random number from 0 to 1000 modulus 3 - 1? ;-)
Bob Cross
I think we should use a randomized recursive Fibonacci function there...
PhiLho
+11  A: 

As Apocalisp wrote, you could do something like:

import java.util.Random;

Random generator = new Random();
int randomIndex = generator.nextInt( 3 ) - 1;
Justin Ethier
Ha! You beat me by seconds! ;-)
Bob Cross
Oh boo, I was totally first. Showing code wins every time.
Apocalisp
Yes, it does. I was hoping to edge out Justin with the javdoc, though. Next time, I should just go for "First P0st!!!111!!@@One!!"
Bob Cross
First post. Then edit it with pointless code and links to the JavaDoc (just in case anyone doesn't have their favourite JavaDoc location bookmarked). Then replace it with a paraphrase of the second person's correct answer.
Tom Hawtin - tackline
Awesome! At least everyone else can be confident the code works since its the same one-liner :)
Justin Ethier
Oh I didn't notice you linked to the javadoc... :(. I voted for this guy cause he had the import statement, which I usually forget to do, causing me to waste 10 minutes trying to find the problem.
But I dont even think the import statement is needed here... w/e
Yeah, my two line solution was waaaaaay better because of the javadoc link.... ;-) To be honest, I never ever think about import statements anymore. Whatever IDE you're using (Netbeans or Eclipse at our office) will just import if / when necessary.
Bob Cross
+3  A: 

This should help:

Random random = new Random();
int value = random.nextInt(3) - 1;
Bob Cross