Sean
Sean

Reputation: 31

Generate Random Number in 2D Array

I am creating a game of Battleships using Java and I am having trouble generating 2 random numbers which randomly choose a place on the battleship board. For example, the computer has to randomly choose a space on the board to place the ships (and later to shoot on).

I have created a 2D array:

int rows = 10;
int cols = 10;
char [][] grid;
grid = new char[rows][cols];

And then tried several different ways to get the two random numbers in the array but I cannot get it to work. Here is an example of what I have tried:

int randomPos = (char) (Math.random() * (grid[rows][cols] + 1));

Please ask me some questions if this doesn't make sense.

Sean

Upvotes: 1

Views: 6573

Answers (4)

fireshadow52
fireshadow52

Reputation: 6516

Math.random() generates a decimal number. It doesn't make any sense to have square 3.5779789689689... (or whatever you're referring to), so use the Math.floor() method, which rounds the number inside to the nearest integer. And as @Sanjay explained, generate the numbers separately...

int row = (int) Math.floor(Math.random() * rows);
int col = (int) Math.floor(Math.random() * cols);

Now you have actual integers that you can work with.

Upvotes: 1

Oscar Gomez
Oscar Gomez

Reputation: 18488

Try this declare this is an ivar:

Random random = new Random();

//In the method do this:

int randomPos = generator.nextInt(11); //This generates a number between 0 and 10.

Upvotes: 0

chubbsondubs
chubbsondubs

Reputation: 38696

int randomRow = Math.random() * grid.length;
int randomColumn = Math.random() * grid[0].length;

I wouldn't use char as my grid type, but the code above works all the same regardless of the types of in the array.

Upvotes: 0

Sanjay T. Sharma
Sanjay T. Sharma

Reputation: 23208

Generate two random numbers separately and use them to index your board. To elaborate:

x = random(max_rows)
y = random(max_cols)
(x, y) -> random location (only if it's not already marked)

In your case, the range of the random number should be between 0 and 9 (inclusive both).

Upvotes: 0

Related Questions