Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random number between -1 and 1?

I am trying to generate a random grid and to represent an empty space, non-empty space and a space where a player is I am using -1, 0 and 1 respectively in a 2D array.

I want to be able to generate a random graph at run time and fill up up the grid with -1's and 0's. How should I go about doing this?

I've looked at some examples but they're confusing :S I know there's a Random class in Java but it doesn't have a method where I can do something like nextInt(-1, 1), where I can set the starting range.

Any help would be great.

Cheers

like image 918
Johnathan Au Avatar asked Dec 18 '25 07:12

Johnathan Au


1 Answers

nextInt(3) -1 will give you a random integer in the desired range.

The random.nextInt(3) will generate a random integer of 0/1/2, and by reducing 1 - you get an equal (uniform) probability to get each of -1/0/1

like image 127
amit Avatar answered Dec 19 '25 22:12

amit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!