Reputation: 3
I'm trying to fill ten random elements in a 2D Array with the character 'B', but some of the elements are being filled more than once---which is making it not fill ten elements like I want.
This is what I am using now:
for(int i = 0; i < 10; i++)
{
board[(int)(Math.random()*(board.length-1))][(int)(Math.random()*(board[0].length-1))] = 'B';
}
Upvotes: 0
Views: 66
Reputation: 683
You may use one dimension list for indexing indexList
, and randomly select index from it index
. Then convert it into row
, col
indexes.
Check this code:
import java.lang.Math; // headers MUST be above the first class
import java.util.Random;
import java.util.ArrayList;
import java.util.List;
// one class needs to have a main() method
public class Fill2DArray
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
int ROWS=3,COLS=3;
Random rand = new Random();
List<Integer> indexList = new ArrayList<>();
for (int i = 0; i < ROWS*COLS ; i++){
indexList.add(i);
}
char[][] board = new char[ROWS][COLS];
for(int i=0; i<ROWS*COLS; i++)
{
int row, col;
int lidx = rand.nextInt(indexList.size());
int index = indexList.get( lidx );
row = index/ROWS;
col = index%ROWS;
board[row][col] = 'B';
indexList.remove(lidx);
}
}
}
Upvotes: 0
Reputation: 89
Where elements is the number of elements to be filled.
For non jagged arrays:
public static void fillElements(char[][] array, int elements) {
if (array.length * array[0].length < elements) throw new IllegalArgumentException();
boolean[][] filled = new boolean[array.length][array[0].length];
int i = 0;
while (i < elements) {
int x = (int) (Math.random() * array.length);
int y = (int) (Math.random() * array[0].length);
if (!filled[x][y]) {
filled[x][y] = true;
array[x][y] = 'B';
i++;
}
}
}
For jagged arrays:
public static void fillElements(char[][] array, int elements) {
int max = 0;
for (int i = 0; i < array.length; i++) {
if (array[i].length > max) {
max = array[i].length;
}
}
if (array.length * max < elements) throw new IllegalArgumentException();
boolean[][] filled = new boolean[array.length][max];
int i = 0;
while (i < elements) {
int x = (int) (Math.random() * array.length);
int y = (int) (Math.random() * array[x].length);
if (!filled[x][y]) {
filled[x][y] = true;
array[x][y] = 'B';
i++;
}
}
}
Upvotes: 1