【问题标题】:Is there a way to reverse specific arrays in a multidimensional array in java?有没有办法在java中的多维数组中反转特定数组?
【发布时间】:2021-03-30 15:41:51
【问题描述】:

我知道如何操作和创建多维数组,但我不知道数组具有的所有实用程序和功能。我想知道如果我有一个大小为[5][4] 的二维数组,我可以在第一行按顺序打印,第二行按顺序打印,第三行按顺序打印......等等。

例如:

[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

正如我的老师所说“定义一个大小为 m × n 的二维数组。编写一个方法来初始化这个数组,其中的数字从 1 到 m × n,方法如下:第一行,从左边开始初始化元素到右;第二行,从右到左初始化;然后切换顺序。例如如果m=5;并且n=4;数组应该初始化为:"

我不确定是否应该使用临时方法或其他循环方法来完成。

【问题讨论】:

    标签: java arrays sorting multidimensional-array


    【解决方案1】:

    你不能直接反转它。但是你可以有一个循环并反转替代行:

    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]));
        }
    }
    

    【讨论】:

      【解决方案2】:

      如果我有一个 [5][4] 大小的二维数组,我可以在 第一行是有序的,第二行是相反的,第三行是在 订单...等等。

      不清楚你想如何使用输出,但这里有一个字面的方式来做到这一点:

      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]);
              }
          }
      }
      

      输出:

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

      【讨论】:

        【解决方案3】:
        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();
        });
        

        此代码使用 Stream API 迭代数组。第一个流迭代单级数组,第二个流迭代它们的元素,然后形成一个字符串。另外,根据计数器值,从左到右或从右到左组合项目。

        【讨论】:

          【解决方案4】:

          您可以使用 流中的流循环中的循环:


          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]
          

          另见:
          How do I rotate a matrix 90 degrees counterclockwise in java?
          Is there any other way to remove all whitespaces in a string?

          【讨论】:

            【解决方案5】:

            效率不如嵌套循环,可以简单地从 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 是模 2,除以 2,因此 0 表示偶数,1 表示奇数。

            或者使用更多的语言特性:

            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);
                });
            

            这里Arrays.setAll(int[], (int index) -&gt; int)根据索引填充数组。

            关于有一些不错的功能的问题:

            你可能见过List.reverse;不存在Arrays.reverse,因此Arrays.setAll 似乎是最好的。在这种情况下,理论上值增加一个也可以对所有奇数行进行排序。但只有一个技巧和分类成本。

            有趣的是有这么多的解决方案。与其摇狗的尾巴,不如拿尾巴摇狗。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-12-04
              • 2022-01-18
              相关资源
              最近更新 更多