Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate Random number in a range 0-8 except one specific number?

Tags:

java

I am trying to develop Tic Tac Toe game where player 1 will click one button to put "X" and later player 2(Computer) will put "O" to other buttons randomly on first step.For that I need to create a random number between 0-8 except the one clicked by player 1.

I am using following code to generate random number

Random random=new Random();
int number=random.nextInt(9);
like image 521
Rinku Chowdhury Avatar asked Mar 02 '14 14:03

Rinku Chowdhury


People also ask

How do you exclude a number in math randomly?

math. random when specified with two values returns a number in the range [m, n]. -1 < 0 < 1 therefore 0 is a valid number in this range. You can't exclude a number, so your best bet would be to do randomise again until the result is not 0.

How do you generate a random number from within a range?

Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.

What methods can be used to get a random number between 0 and 1?

We can simply use Math. random() method to get random number between 0 to 1. Math. random method returns double value between o(inclusive) to 1(exclusive).


1 Answers

If you want random numbers from 0 to 8 with one value excluded, then there are really 8 possible values, not 9. So generate a random number from 0 to 7 — random.nextInt(8) — and if the result is greater than or equal to your excluded value, add 1 to it.

like image 159
Wyzard Avatar answered Oct 09 '22 15:10

Wyzard