如何生成每个元素都不相同的4X4 2D数组表?
这是我的代码:
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();
}
}
}
答案 0 :(得分:0)
您可以使用Set
第一得到没有重复,然后一个List
容易地访问它们
Set<Integer> set = new LinkedHashSet<>();
int gameboard[][] = new int[4][4];
while(set.size() != 4*4){
set.add((int)(1+Math.random() * 16));
}
List<Integer> list = new ArrayList<>(set);
for (int row=0; row < gameboard.length; row++) {
for (int col=0; col < gameboard[row].length; col++) {
gameboard[row][col] = list.get(row*gameboard.length + col);
System.out.printf("%-4d",gameboard[row][col]);
}
System.out.println();
}
}
答案 1 :(得分:0)
您只需要在以下位置放置一个控件即可:
int a == gameboard[row][col];
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));
if(gameboard[row][col] == a){
col = col - 1;
}
}
}
答案 2 :(得分:0)
解决方案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();
}
}
在每次迭代中,我们检查 set 中是否存在生成的随机数。如果存在,那么我们将循环运行,直到获得集合中不存在的其他随机数。
解决方案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();
}
在这里,我们生成一个数字列表,然后使用 Collections.shuffle()对其进行洗牌。现在,我们遍历多维数组,并将列表的值分配给该数组。