首先按列填充一个锯齿状的二维数组 [英] Filling a jagged 2d array first by columns
本文介绍了首先按列填充一个锯齿状的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想编写一个函数,该函数需要一个2d数组,并用 1 ... n
填充它,但首先要计算列数而不是行数:
I want to write a function that takes an 2d array and fills it with 1...n
but counting the columns first instead of the rows:
input = {{0, 0, 0, 0}, {0}, {0}, {0, 0}};
the output should be: {{1, 5, 7, 8}, {2}, {3}, {4, 6}};
如果我要遍历行,然后获得列,我会得到:
if i were to loop through rows and then colums i get:
private static void fill1(int[][] input) {
int count = 1;
for (int i = 0; i < input.length; i++) {
for (int j = 0; j < input[i].length; j++) {
input[i][j] = count;
count++;
}
}
}
我如何首先遍历各栏?
推荐答案
要首先遍历锯齿状2d数组的列以填充它,您必须事先知道最大列数,但是如果不知道这样,您可以迭代到 Integer.MAX_VALUE
,并在每一步检查列是否仍然存在:
To iterate first over the columns of a jagged 2d array to fill it, you have to know the maximum number of columns beforehand, but if you don't know that, you can iterate to the Integer.MAX_VALUE
and check at each step if the columns are still present or not:
int[][] arr = {{0, 0, 0, 0}, {0}, {0}, {0, 0}};
int count = 1;
for (int col = 0; col < Integer.MAX_VALUE; col++) {
boolean max = true;
for (int row = 0; row < arr.length; row++) {
if (col < arr[row].length) {
arr[row][col] = count;
count++;
max = false;
}
}
if (max) break;
}
for (int[] row : arr) {
System.out.println(Arrays.toString(row));
}
输出:
[1, 5, 7, 8]
[2]
[3]
[4, 6]
这篇关于首先按列填充一个锯齿状的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文