I am doing a Bingo program and now, the section of the bingoCard, to do this I am using an a bidimensional array but I need to shuffle the numbers of each row. For the shuffle part I saw that the setList is much better, but I don't know how to relate the List with the array here is a part of the code:
public static Integer[][] bingoCard(){
Integer [][] bingoCard= new Integer[3][9];
for(int x =0; x<bingoCard.length; x ){
for(int y =0; y<bingoCard[x].length; y ){
if(y <5){
int random = (int)(Math.random()*90 1);
System.out.print((bingoCard[0][y] = random) " ");
}
if(y >4 && y <9){
System.out.print((bingoCard[0][y] = 0) " ");
}
}
System.out.println();
}
List<Integer[]> list =Arrays.asList(bingoCard);
Collections.shuffle(list);
list.toArray(bingoCard);
return bingoCard;
}
Any question please ask me!! Thanks.
CodePudding user response:
In your code, when you do List<Integer[]> list = Arrays.asList(bingoCard)
, you are converting the outer array into a List
and then shuffling its contents. The effect of this will be that the order of the 3 rows are shuffled rather than the contents of the 3 rows which is what you want. You could achieve this by shuffling the contents of each row within your for-loop. Or, after constructing the 2D array, you can loop over each row again and shuffle them.
Also, you have another small bug. When you assign the value, you are doing bingoCard[0][y] = ...
but it should be bingoCard[x][y]
. Otherwise, you are only assigning the first row new values on each iteration.
I would recommend not converting the array to a List
just to shuffle it and then converting it back. Instead, you can use Random.nextInt
to pick indexes of the array to assign. That would look something like this:
public static Integer[][] bingoCard(){
int numRows = 3;
int numCols = 9;
int randomNumbersPerRow = 5;
int randomNumberBound = 90;
Random random = new Random();
Integer[][] bingoCard = new Integer[numRows][numCols];
for (int row = 0; row < numRows; row ) {
for (int col = 0; col < numCols; col ) {
// Initialize all spots to 0
bingoCard[row][col] = 0;
}
for (int i = 0; i < randomNumbersPerRow; i ) {
// Choose a spot to assign a random number
int indexToAssign = random.nextInt(numCols);
// Make sure we haven't already chosen it
while (bingoCard[row][indexToAssign] != 0) {
indexToAssign = random.nextInt(numCols);
}
int numToAssign = random.nextInt(randomNumberBound) 1;
bingoCard[row][indexToAssign] = numToAssign;
}
}
// Print the bingo card
for (int row = 0; row < numRows; row ) {
for (int col = 0; col < numCols; col ) {
System.out.printf("- ", bingoCard[row][col]);
}
System.out.println();
}
return bingoCard;
}