有没有办法用唯一的随机数填充二维数组?我做了很多尝试,但是所有尝试都失败了。 我可以做到
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i < 26; i++) { //element will be in range (1,25)
list.add(i);
}
Collections.shuffle(list);
for (int j = 0; j < 5; j++) {
System.out.print(list.get(j) + " ");
}
System.out.println();
答案 0 :(得分:1)
我想您可以结合使用生成随机数和哈希集的库。哈希集可记住到目前为止生成的随机数,如果生成重复数,则重新生成,直到它给出看不见的数字为止
答案 1 :(得分:1)
如果要从List
打印5x5的数字矩阵,则只需要两层for
循环。请参阅下面的代码here。
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i < 26; i++) { // element will be in range (1,25)
list.add(i);
}
Collections.shuffle(list);
for (int j = 0; j < 5; j++) {
for (int k = 0; k < 5; k++) {
System.out.format("%3d ", list.get(j * 5 + k));
}
System.out.println();
}
System.out.println();
示例输出:
3 4 23 18 15
1 8 20 6 7
5 21 19 2 24
17 13 22 16 25
14 9 12 10 11
答案 2 :(得分:1)
尝试一下。
static List<List<Integer>> uniqueRandomNumbers(int height, int width) {
List<Integer> list = IntStream.rangeClosed(1, height * width)
.boxed()
.collect(Collectors.toList());
Collections.shuffle(list);
List<List<Integer>> matrix = IntStream.range(0, height)
.mapToObj(i -> list.subList(i * width, (i + 1) * width))
.collect(Collectors.toList());
return matrix;
}
和
List<List<Integer>> matrix = uniqueRandomNumbers(5, 5);
for (List<Integer> list : matrix)
System.out.println(list);
结果
[16, 4, 15, 14, 25]
[19, 11, 6, 21, 9]
[17, 20, 3, 1, 5]
[10, 7, 22, 18, 2]
[12, 13, 24, 23, 8]
答案 3 :(得分:0)
这可以帮助吗?
public static void main(String[] args)
{
// declare arrays
int[][] ticketInfo;
String[][] seatingChart;
// create arrays
ticketInfo = new int [2][3];
seatingChart = new String [3][2];
// initialize the array elements
ticketInfo[0][0] = 15;
ticketInfo[0][1] = 10;
ticketInfo[0][2] = 15;
ticketInfo[1][0] = 25;
ticketInfo[1][1] = 20;
ticketInfo[1][2] = 25;
seatingChart[0][0] = "Jamal";
seatingChart[0][1] = "Maria";
seatingChart[1][0] = "Jacob";
seatingChart[1][1] = "Suzy";
seatingChart[2][0] = "Emma";
seatingChart[2][1] = "Luke";
// print the contents
System.out.println(ticketInfo);
System.out.println(seatingChart);
}