简体   繁体   English

有没有办法在 java 的多维数组中反转特定的 arrays?

[英]Is there a way to reverse specific arrays in a multidimensional array in java?

I know how to generally manipulate and create a multidimensional array but I don't know all the utils and features that arrays have.我知道如何操作和创建多维数组,但我不知道 arrays 拥有的所有实用程序和功能。 I want to know is if I have a 2D array the size of [5][4] , can I print it where the first line is in order, second is in reverse, and the third is in order... and so on.我想知道如果我有一个大小为[5][4]的二维数组,我可以在第一行按顺序打印,第二行按顺序打印,第三行按顺序打印...等等.

For example:例如:

[1 2 3 4] //in order
[8 7 6 5] //reverse
[9 10 11 12] //in order
[16 15 14 13] //reverse
[17 18 19 20] //in order

as my teacher stated "Define a two-dimensional array of size m × n. Write a method to initialize this array with numbers from 1 to m × n in the way as below: the first row, initialize the elements from left to right; the second row, initialize from right to left; then switch order. For example, if m=5; and n = 4; the array should be initialized to:"正如我的老师所说“定义一个大小为 m × n 的二维数组。编写一个方法,用 1 到 m × n 的数字初始化这个数组,方法如下:第一行,从左到右初始化元素;第二行,从右到左初始化;然后切换顺序。例如,如果m=5;并且n=4;数组应该初始化为:"

I'm not sure if it should be done using a temp method or some other loop method.我不确定是否应该使用临时方法或其他循环方法来完成。

You cannot reverse it directly.你不能直接反转它。 But you can have a loop and reverse the alternative rows:但是您可以有一个循环并反转替代行:

void reverseArray() {
    Integer[][] arr = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 16},
            {17, 18, 19, 20}};
    for (int i = 1; i < arr.length; i += 2) {
        Collections.reverse(Arrays.asList(arr[i]));
    }
}
int[][] arr = new int[][]{
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}};

AtomicInteger counter = new AtomicInteger(0);
Arrays.stream(arr).forEach(ints -> {
    System.out.println(Arrays.stream(ints)
            .mapToObj(String::valueOf)
            .reduce((a, b) ->
                    counter.get() % 2 == 0 ? a + " " + b : b + " " + a).get());
    counter.incrementAndGet();
});

This code uses the Stream API to iterate over an array.此代码使用 Stream API 迭代数组。 The first stream iterates over single-level arrays, the second - their elements, and then forms a string.第一个 stream 迭代单级 arrays,第二个 - 它们的元素,然后是 forms 一个字符串。 Also, according to the counter value, items are combined from left to right or from right to left.此外,根据计数器值,从左到右或从右到左组合项目。

You can create such an array with a "snake order" without sorting at all, using a stream in a stream or a loop in a loop :您可以使用stream 中的 stream循环中的循环来创建这样的数组,而无需排序:


  1.  int m = 5; int n = 4; int[][] arr = IntStream // create rows of array.range(0, m).mapToObj(row -> IntStream // for each row create cells where // values are numbers from 1 to [m * n].range(0, n).map(cell -> { int val = row * n; if (row % 2 == 0) // even rows: // straight order val += cell + 1; else // odd rows: // reverse order val += n - cell; return val; }) // return int[] array.toArray()) // return int[][] 2d array.toArray(int[][]::new);

  1.  int m = 5; int n = 4; int[][] arr = new int[m][n]; // create rows of array for (int row = 0; row < m; row++) { // for each row create cells where // values are numbers from 1 to [m * n] for (int cell = 0; cell < n; cell++) { int val = row * n; if (row % 2 == 0) // even rows: // straight order val += cell + 1; else // odd rows: // reverse order val += n - cell; arr[row][cell] = val; } }

Arrays.stream(arr).map(Arrays::toString).forEach(System.out::println);
// [1, 2, 3, 4]
// [8, 7, 6, 5]
// [9, 10, 11, 12]
// [16, 15, 14, 13]
// [17, 18, 19, 20]

See also:也可以看看:
How do I rotate a matrix 90 degrees counterclockwise in java? 如何在 java 中将矩阵逆时针旋转 90 度?
Is there any other way to remove all whitespaces in a string? 有没有其他方法可以删除字符串中的所有空格?

if I have a 2D array the size of [5][4], can I print it where the first line is in order, second is in reverse, and the third is in order... and so on.如果我有一个 [5][4] 大小的二维数组,我可以在第一行按顺序打印,第二行按顺序打印,第三行按顺序打印...等等。

It's unclear how you want to use the output, but here is a literal way to do it:目前还不清楚你想如何使用 output,但这里有一个字面的方法:

public static void main(String[] args) {
    int[][] values = new int[][]{
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 16}
    };

    for (int r = 0; r < values.length; r++) {
        if (r % 2 == 0) {
            // forwards
            for (int c = 0; c < (values[r].length - 1); c++) {
                System.out.print(values[r][c] + " ");
            }
            System.out.println(values[r][values[r].length - 1]);
        } else {
            // backwards
            for (int c = (values[r].length - 1); c > 0; c--) {
                System.out.print(values[r][c] + " ");
            }
            System.out.println(values[r][0]);
        }
    }
}

Output: Output:

1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13

Not as efficient as nested loops, one can simply iterator from 1 to 20 and determine row i and column j .不如嵌套循环高效,可以简单地从 1 迭代到 20 并确定第i行和第j列。

final int M = 5;
final int N = 4;
int[][] matrix = new int[M][N];

IntStream.range(0, M*N)
    .forEach(no -> { // no = 0, 1, 2, ... , M*N-1
        int i = no / N; // Row.
        int j = no % N; // Increasing column (for even row).
        if (i % 2 == 1) { // Odd row.
           j = N - 1 - j; // Decreasing column.
        }
        matrix[i][j] = no + 1;
    });

i % 2 is the modulo 2, rest by division of 2, hence 0 for even, 1 for odd. i % 2是模 2,rest 除以 2,因此 0 表示偶数,1 表示奇数。

Or use a bit more language features:或者使用更多的语言功能:

IntStream.range(0, N)
    .forEach(i -> {
        int no = N * i;
        IntUnaryOperator jToValue = i % 2 == 0
            ? j -> no + 1 + j
            : j -> no + N - 1 -j;
        Arrays.setAll(matrix[i], jToValue);
    });

Here Arrays.setAll(int[], (int index) -> int) fills the array based on the index.这里Arrays.setAll(int[], (int index) -> int)根据索引填充数组。

About the question of there being some nice function:关于有一些不错的function的问题:

You probably saw List.reverse ;你可能看过List.reverse there does not exist an Arrays.reverse , hence Arrays.setAll seems to be best.不存在Arrays.reverse ,因此Arrays.setAll似乎是最好的。 In this case where the values are increasing one theoretically could also sort all odd rows reversed.在这种情况下,理论上值增加一个也可以对所有奇数行进行排序。 But only with a trick, and sorting costs.但只有一个技巧和分类成本。

It is interesting that there are so many solutions.有趣的是有这么多的解决方案。 Instead of waggling the dog's tail one can take the tail and waggle the dog.与其摆动狗的尾巴,不如拿起尾巴摆动狗。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM