user10947891:
¿Cómo debería generar una tabla matriz 4X4 2D con cada elemento diferente?
Aquí está mi código:
public class Game {
public static void main(String[] args) {
int gameboard[][] = new int[4][4];
for (int row=0; row < gameboard.length; row++) {
for (int col=0; col < gameboard[row].length; col++) {
gameboard[row][col] = ((int)(1+Math.random() * 16));
System.out.printf("%-4d",gameboard[row][col]);
}
System.out.println();
}
}
}
Nicholas K:
Solución 1:
public static void main(String[] s1) throws Exception {
int gameboard[][] = new int[4][4];
Set<Integer> mySet = new HashSet<>();
for (int row = 0; row < gameboard.length; row++) {
for (int col = 0; col < gameboard[row].length; col++) {
int randNum = (int) (1 + Math.random() * 16);
while (mySet.contains(randNum)) {
randNum = (int) (1 + Math.random() * 16);
}
mySet.add(randNum);
gameboard[row][col] = randNum;
System.out.printf("%-4d", gameboard[row][col]);
}
System.out.println();
}
}
Aquí, en cada iteración, comprobamos si el número aleatorio generado está presente en el conjunto . Si está presente, entonces nos bucle hasta que consigamos un número aleatorio diferente que no está presente en el conjunto.
Solución 2:
List<Integer> myList = IntStream.range(1, 17).boxed().collect(Collectors.toList());
Collections.shuffle(myList);
for (int row = 0; row < gameboard.length; row++) {
for (int col = 0; col < gameboard[row].length; col++) {
gameboard[row][col] = myList.get(row * gameboard.length + col);
System.out.printf("%-4d", gameboard[row][col]);
}
System.out.println();
}
Aquí se genera una lista de números y luego baraja usando Collections.shuffle () . Ahora iteramos sobre la matriz multidimensional y asignamos los valores de la lista a la matriz.