本文介绍了首先按列填充锯齿状的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个函数,它接受一个二维数组并用 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++;
        }
    }
}

如何首先遍历列?

推荐答案

要首先按列填充二维数组,您可以使用两个嵌套的.在锯齿状二维数组的情况下,当您事先不知道每行中的列数时,您可以在列仍然存在的情况下遍历外部流.

To populate a 2d array first by columns, you can use two nested streams. In case of a jagged 2d array, when you don't know beforehand the number of the columns in each row, in an outer stream you can traverse while the columns are still present.

/**
 * @param arr array that should be populated.
 * @return maximum row length, i.e. columns count.
 */
private static long populate(int[][] arr) {
    AtomicInteger counter = new AtomicInteger(1);
    return IntStream
            // traverse through the array columns
            .iterate(0, i -> i + 1)
            // process the array rows where
            // this column is present
            .mapToLong(i -> Arrays.stream(arr)
                    // filter those rows where
                    // this column is present
                    .filter(row -> row.length > i)
                    // assign a value to the element and increase the counter
                    .peek(row -> row[i] = counter.getAndIncrement())
                    // count of rows where this column is present
                    .count())
            // while the columns are still present
            .takeWhile(i -> i > 0)
            // max columns count
            .count();
}
public static void main(String[] args) {
    int[][] arr = {{0, 0, 0, 0, 0, 0}, {0, 0}, {0}, {0, 0, 0}};

    System.out.println("Max columns count: " + populate(arr));
    System.out.println(Arrays.deepToString(arr));
}

输出:

Max columns count: 6
[[1, 5, 8, 10, 11, 12], [2, 6], [3], [4, 7, 9]]


另见:如何以循环方式合并 3 个 ArrayList 来创建新列表?上>

这篇关于首先按列填充锯齿状的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 14:21