【问题标题】:How can I read matrix array different way in Java?如何在 Java 中以不同的方式读取矩阵数组?
【发布时间】:2020-08-18 16:59:06
【问题描述】:

我有一个 8x8 矩阵数组。我想读取如图所示的矩阵值(元素)。 我能做到吗?

我已经定义了这样的数组。

public static void main(String args[]) {
    int[][] myArray = new int[8][8];

    int start = 0;

    for (int i = 0; i<8; i++){
        for (int j = 0; j<8; j++) {
            myArray[i][j] = start;
            start++;
        }
    }
}

【问题讨论】:

  • 到目前为止你尝试过什么?你为什么要按这个顺序读入数据?
  • 您是否正在寻找任何维度的矩阵的解决方案?它必须是方阵吗? (即行数等于列数)
  • 我的项目需要这个。行数和列数并不总是相等的。
  • 我们不是家庭作业代写服务。
  • 这不是作业兄弟????????

标签: java arrays matrix


【解决方案1】:
public static List<Integer> readMatrix(int[][] matrix) {
    int totalRows = matrix.length;
    int totalCols = matrix[0].length;

    List<Integer> res = new ArrayList<>(totalRows * totalCols);
    List<Integer> diagonal = new ArrayList<>(Math.max(totalRows, totalCols));

    boolean reverseOrder = true;

    for (int col = totalCols - 1; col >= 0; col--) {
        for (int row = 0; row < totalRows && col + row < totalCols; row++)
            diagonal.add(matrix[row][col + row]);

        if (reverseOrder)
            Collections.reverse(diagonal);

        res.addAll(diagonal);
        reverseOrder = !reverseOrder;
        diagonal.clear();
    }

    for (int row = 1; row < totalRows; row++) {
        for (int col = 0; col < totalCols && col + row < totalRows; col++)
            diagonal.add(matrix[col + row][col]);

        if (reverseOrder)
            Collections.reverse(diagonal);

        res.addAll(diagonal);
        reverseOrder = !reverseOrder;
        diagonal.clear();
    }

    return res;
}

【讨论】:

    【解决方案2】:

    这是我的解决方案。代码包含解释遍历算法的 cmets。

    public class MatrixTraversal {
        private static int[][]  matrix;
    
        private static void displayElement(int row, int col, int length, int count) {
            System.out.printf("%" + length + "d. Next  element [%" + length + "d][%" + length + "d] = %" + length + "d%n",
                              (count + 1),
                              row,
                              col,
                              matrix[row][col]);
        }
    
        private static void displayMatrix() {
            int length = getLength();
            for (int i = 0; i < matrix.length; i++) {
                for (int j = 0; j < matrix[i].length; j++) {
                    if (j > 0  &&  j < matrix[i].length) {
                        System.out.print(" ");
                    }
                    System.out.printf("%" + length + "d", matrix[i][j]);
                }
                System.out.println();
            }
            System.out.println();
        }
    
        private static int getLength() {
            int rows = matrix.length;
            int cols = matrix[0].length;
            int number = rows * cols;
            int length = (int) (Math.log10(number) + 1);
            return length;
        }
    
        private static void initMatrix(int rows, int cols) {
            System.out.printf("rows = %d , columns = %d%n", rows, cols);
            System.out.println();
            if (rows > 0  &&  cols > 0) {
                matrix = new int[rows][cols];
                for (int row = 0; row < rows; row++) {
                    for (int col = 0; col < cols; col++) {
                        matrix[row][col] = (row * cols) + col;
                    }
                }
                displayMatrix();
            }
            else {
                throw new IllegalArgumentException("rows and columns must both be positive");
            }
        }
    
        // Algorithm:
        // 1. Start at first row, last column.
        // 2. Go to same row, column to left.
        //    a. If can't go left, go down one row, i.e. same column, next row.
        //    b. If can't go left, go to step 3.
        // 3. Go diagonally down and to the right until reach either last row or last column.
        //    a. If can't go diagonally down and to the right, go to 4.
        // 4. Go to same column, next row.
        //    a. If can't go down, go left, i.e. same row, column to left.
        //    b. If can't go left, go to step 5.
        // 5. Go diagonally up and to the left until reach either first row or first column.
        //    a. If can't go diagonally up and to the left, go to 6.
        // 6. Go back to step 2.
        // 7. Finish at last row, first column.
        private static void traverse() {
            int length = getLength();
            int total = matrix.length * matrix[0].length;
            System.out.println("Total = " + total);
            int row = 0;
            int col = matrix[row].length - 1;
            System.out.println("Start col = " + col);
            int count = 0;
            System.out.printf("%" + length + "d. First element [%" + length + "d][%" + length + "d] = %" + length + "d%n",
                              1,
                              row,
                              col,
                              matrix[row][col]);
            count++;
            while (count < total) {
                if (col - 1 >= 0) {
                    col--;
                    displayElement(row, col, length, count);
                    count++;
                }
                else {
                    if (row < matrix.length - 1) {
                        row++;
                        displayElement(row, col, length, count);
                        count++;
                    }
                }
                while (row < matrix.length - 1  &&  col < matrix[row].length - 1) {
                    row++;
                    col++;
                    displayElement(row, col, length, count);
                    count++;
                }
                if (row < matrix.length - 1) {
                    row++;
                    displayElement(row, col, length, count);
                    count++;
                }
                else {
                    if (col - 1 >= 0) {
                        col--;
                        displayElement(row, col, length, count);
                        count++;
                    }
                }
                while (row > 0  &&  col > 0) {
                    row--;
                    col--;
                    displayElement(row, col, length, count);
                    count++;
                }
            }
        }
    
        /**
         * Requires following two <tt>java</tt> command arguments (in listed order):
         * <ol>
         * <li>number of rows in matrix</li>
         * <li>number of columns in matrix</li>
         * </ol>
         * 
         * @param args - <tt>java</tt> command arguments.
         */
        public static void main(String[] args) {
            if (args.length > 1) {
                int rows = Integer.parseInt(args[0]);
                int cols = Integer.parseInt(args[1]);
                initMatrix(rows, cols);
                traverse();
            }
            else {
                System.out.println("ARGS: <# of rows in matrix> <# of columns in matrix>");
            }
        }
    }
    

    在不同维度上进行了测试,包括一行多列和一列多行。这是一个 8x8 矩阵的输出。

    rows = 8 , columns = 8
    
     0  1  2  3  4  5  6  7
     8  9 10 11 12 13 14 15
    16 17 18 19 20 21 22 23
    24 25 26 27 28 29 30 31
    32 33 34 35 36 37 38 39
    40 41 42 43 44 45 46 47
    48 49 50 51 52 53 54 55
    56 57 58 59 60 61 62 63
    
    Total = 64
    Start col = 7
     1. First element [ 0][ 7] =  7
     2. Next  element [ 0][ 6] =  6
     3. Next  element [ 1][ 7] = 15
     4. Next  element [ 2][ 7] = 23
     5. Next  element [ 1][ 6] = 14
     6. Next  element [ 0][ 5] =  5
     7. Next  element [ 0][ 4] =  4
     8. Next  element [ 1][ 5] = 13
     9. Next  element [ 2][ 6] = 22
    10. Next  element [ 3][ 7] = 31
    11. Next  element [ 4][ 7] = 39
    12. Next  element [ 3][ 6] = 30
    13. Next  element [ 2][ 5] = 21
    14. Next  element [ 1][ 4] = 12
    15. Next  element [ 0][ 3] =  3
    16. Next  element [ 0][ 2] =  2
    17. Next  element [ 1][ 3] = 11
    18. Next  element [ 2][ 4] = 20
    19. Next  element [ 3][ 5] = 29
    20. Next  element [ 4][ 6] = 38
    21. Next  element [ 5][ 7] = 47
    22. Next  element [ 6][ 7] = 55
    23. Next  element [ 5][ 6] = 46
    24. Next  element [ 4][ 5] = 37
    25. Next  element [ 3][ 4] = 28
    26. Next  element [ 2][ 3] = 19
    27. Next  element [ 1][ 2] = 10
    28. Next  element [ 0][ 1] =  1
    29. Next  element [ 0][ 0] =  0
    30. Next  element [ 1][ 1] =  9
    31. Next  element [ 2][ 2] = 18
    32. Next  element [ 3][ 3] = 27
    33. Next  element [ 4][ 4] = 36
    34. Next  element [ 5][ 5] = 45
    35. Next  element [ 6][ 6] = 54
    36. Next  element [ 7][ 7] = 63
    37. Next  element [ 7][ 6] = 62
    38. Next  element [ 6][ 5] = 53
    39. Next  element [ 5][ 4] = 44
    40. Next  element [ 4][ 3] = 35
    41. Next  element [ 3][ 2] = 26
    42. Next  element [ 2][ 1] = 17
    43. Next  element [ 1][ 0] =  8
    44. Next  element [ 2][ 0] = 16
    45. Next  element [ 3][ 1] = 25
    46. Next  element [ 4][ 2] = 34
    47. Next  element [ 5][ 3] = 43
    48. Next  element [ 6][ 4] = 52
    49. Next  element [ 7][ 5] = 61
    50. Next  element [ 7][ 4] = 60
    51. Next  element [ 6][ 3] = 51
    52. Next  element [ 5][ 2] = 42
    53. Next  element [ 4][ 1] = 33
    54. Next  element [ 3][ 0] = 24
    55. Next  element [ 4][ 0] = 32
    56. Next  element [ 5][ 1] = 41
    57. Next  element [ 6][ 2] = 50
    58. Next  element [ 7][ 3] = 59
    59. Next  element [ 7][ 2] = 58
    60. Next  element [ 6][ 1] = 49
    61. Next  element [ 5][ 0] = 40
    62. Next  element [ 6][ 0] = 48
    63. Next  element [ 7][ 1] = 57
    64. Next  element [ 7][ 0] = 56
    

    【讨论】:

      【解决方案3】:

      您如何解决任何编码问题?一步一个脚印。

      按照你图片中的路径,我们列出前几个整数数组下标。

      0, 7
      0, 6
      1, 7
      2, 7
      1, 6
      0, 5
      0, 4
      1, 5
      2, 6
      3, 7
      

      您需要列出足够多的下标才能看到发展的模式。

      一种可能的解决方案是将下标编码到不同的数组中。不幸的是,此解决方案会将您锁定在 8 x 8 矩阵中。

      所以,让我们编写一些代码来获取矩阵的前几个值。它不会是漂亮的代码。我们仍在尝试找出模式。

      import java.util.Arrays;
      
      public class ArrayWalk {
      
          public static void main(String args[]) {
              int height = 8;
              int width = 8;
      
              ArrayWalk aw = new ArrayWalk();
              int[][] myArray = aw.createArray(height, width);
              int[] values = aw.walkArray(myArray);
      
              System.out.println(Arrays.toString(values));
          }
      
          private int[][] createArray(int height, int width) {
              int[][] myArray = new int[height][width];
      
              int start = 0;
      
              for (int h = 0; h < height; h++) {
                  for (int w = 0; w < width; w++) {
                      myArray[h][w] = start;
                      start++;
                  }
              }
      
              return myArray;
          }
      
          private int[] walkArray(int[][] myArray) {
              int height = myArray.length;
              int width = myArray[0].length;
              int length = height * width;
              int[] values = new int[length];
              int index = 0;
      
              int h = 0;
              int w = width - 1;
              values[index++] = myArray[h][w];
      
              w--;
              values[index++] = myArray[h][w];
      
              h++;
              w++;
              values[index++] = myArray[h][w];
      
              h++;
              values[index++] = myArray[h][w];
      
              h--;
              w--;
              values[index++] = myArray[h][w];
      
              h--;
              w--;
              values[index++] = myArray[h][w];
      
              w--;
              values[index++] = myArray[h][w];
      
              h++;
              w++;
              values[index++] = myArray[h][w];
      
              h++;
              w++;
              values[index++] = myArray[h][w];
      
              h++;
              w++;
              values[index++] = myArray[h][w];
      
              h++;
              values[index++] = myArray[h][w];
      
              h--;
              w--;
              values[index++] = myArray[h][w];
      
              h--;
              w--;
              values[index++] = myArray[h][w];
      
              h--;
              w--;
              values[index++] = myArray[h][w];
      
              h--;
              w--;
              values[index++] = myArray[h][w];
      
              return values;
          }
      
      }
      

      如您所见,我们已经确定需要设置矩阵的宽度和高度,并且需要返回一个整数数组来保存矩阵值。

      到目前为止,一切都很好。

      更重要的是,我们看到了一种模式的发展。我们只看下标。

      w--
      
      h++
      w++   (once)
      
      h++
      
      h--
      w--   (twice)
      

      此模式重复,但双下标重复一次、两次、三次,最多七次(宽度 - 一次)。然后双下标重复六、五、四等次。

      顶行和底行总是向左移动。第一列和最后一列总是向下移动。

      现在,在这一点上,我不确定我刚才所说的是否适用于矩形矩阵。我很确定它适用于方阵。

      让我们用我们获得的知识编写一个辅助方法。这种模式是工厂模式。

      private Dimension[] createIncrements() {
          Dimension[] increments = new Dimension[4];
          increments[0] = new Dimension(-1, 0);
          increments[1] = new Dimension(1, 1);
          increments[2] = new Dimension(0, 1);
          increments[3] = new Dimension(-1, -1);
          return increments;
      }
      

      java.awt.Dimension 包含一个宽度和一个高度。因此,我们定义了在 Code Pattern 中看到的四个增量。然后我们可以循环通过这些增量。诀窍是跟踪我们需要使用第一个和第三个(从零开始的)增量来增加多少次。我们必须从 1 数到 7,然后再倒数到 1。

      我已经尝试了几个小时。这是一个很难解决的问题。明天我会从上次停下的地方继续。

      希望到目前为止我给您的描述对您有所帮助。

      编辑添加:我不确定我是否会在其他答案中提出算法。我最终所做的只是编写一些代码来测试不同的数组大小。

      这是一项测试的结果。

      -------------------
      |   0 |   1 |   2 |
      -------------------
      |   3 |   4 |   5 |
      -------------------
      |   6 |   7 |   8 |
      -------------------
      
      [2, 1, 5, 8, 4, 0, 3, 7, 6]
      

      另一个测试

      -------------------------------
      |   0 |   1 |   2 |   3 |   4 |
      -------------------------------
      |   5 |   6 |   7 |   8 |   9 |
      -------------------------------
      
      [4, 3, 9, 8, 2, 1, 7, 6, 0, 5]
      

      最后,图片中的 8 x 8 测试。

      -------------------------------------------------
      |   0 |   1 |   2 |   3 |   4 |   5 |   6 |   7 |
      -------------------------------------------------
      |   8 |   9 |  10 |  11 |  12 |  13 |  14 |  15 |
      -------------------------------------------------
      |  16 |  17 |  18 |  19 |  20 |  21 |  22 |  23 |
      -------------------------------------------------
      |  24 |  25 |  26 |  27 |  28 |  29 |  30 |  31 |
      -------------------------------------------------
      |  32 |  33 |  34 |  35 |  36 |  37 |  38 |  39 |
      -------------------------------------------------
      |  40 |  41 |  42 |  43 |  44 |  45 |  46 |  47 |
      -------------------------------------------------
      |  48 |  49 |  50 |  51 |  52 |  53 |  54 |  55 |
      -------------------------------------------------
      |  56 |  57 |  58 |  59 |  60 |  61 |  62 |  63 |
      -------------------------------------------------
      
      [7, 6, 15, 23, 14, 5, 4, 13, 22, 31, 39, 30, 21, 12, 3, 2, 11, 20, 29, 38, 
      47, 55, 46, 37, 28, 19, 10, 1, 0, 9, 18, 27, 36, 45, 54, 63, 62, 53, 44, 35, 
      26, 17, 8, 16, 25, 34, 43, 52, 61, 60, 51, 42, 33, 24, 32, 41, 50, 59, 58, 
      49, 40, 48, 57, 56]
      

      这是代码。

      import java.util.ArrayList;
      import java.util.Arrays;
      import java.util.Collections;
      import java.util.List;
      
      public class ArrayWalk {
      
          public static void main(String args[]) {
              int height = 8;
              int width = 8;
      
              ArrayWalk aw = new ArrayWalk();
              int[][] myArray = aw.createArray(height, width);
              System.out.println(aw.printArray(myArray));
      
              int[] values = aw.walkArray(myArray);
              System.out.println(Arrays.toString(values));
          }
      
          private int[][] createArray(int height, int width) {
              int[][] myArray = new int[height][width];
      
              int start = 0;
      
              for (int h = 0; h < height; h++) {
                  for (int w = 0; w < width; w++) {
                      myArray[h][w] = start;
                      start++;
                  }
              }
      
              return myArray;
          }
      
          private int[] walkArray(int[][] myArray) {
              int totalRows = myArray.length;
              int totalCols = myArray[0].length;
      
              List<Integer> res = new ArrayList<>(totalRows * totalCols);
              List<Integer> diagonal = new ArrayList<>(
                      Math.max(totalRows, totalCols));
      
              boolean reverseOrder = true;
      
              for (int col = totalCols - 1; col >= 0; col--) {
                  for (int row = 0; row < totalRows && col + row < totalCols; row++) {
                      diagonal.add(myArray[row][col + row]);
                  }
      
                  if (reverseOrder) {
                      Collections.reverse(diagonal);
                  }
      
                  res.addAll(diagonal);
                  reverseOrder = !reverseOrder;
                  diagonal.clear();
              }
      
              for (int row = 1; row < totalRows; row++) {
                  for (int col = 0; col < totalCols && col + row < totalRows; col++) {
                      diagonal.add(myArray[col + row][col]);
                  }
      
                  if (reverseOrder) {
                      Collections.reverse(diagonal);
                  }
      
                  res.addAll(diagonal);
                  reverseOrder = !reverseOrder;
                  diagonal.clear();
              }
      
              int[] output = new int[res.size()];
              for (int i = 0; i < res.size(); i++) {
                  output[i] = res.get(i);
              }
              return output;
          }
      
          private String printArray(int[][] myArray) {
              String output = "";
              for (int h = 0; h < myArray.length; h++) {
                  output += printDashes(myArray[h].length) + "\n";
                  output += printLine(myArray[h]) + "\n";
              }
              output += printDashes(myArray[0].length) + "\n";
              return output;
          }
      
          private String printDashes(int width) {
              int count = width * 6 + 1;
              String output = "";
      
              for (int i = 0; i < count; i++) {
                  output += "-";
              }
      
              return output;
          }
      
          private String printLine(int[] array) {
              String output = "|";
      
              for (int i = 0; i < array.length; i++) {
                  String value = String.format("%3d", array[i]);
                  output += " " + value + " |";
              }
      
              return output;
          }
      
      }
      

      【讨论】:

      • 谢谢兄弟。工作精湛??
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      • 1970-01-01
      相关资源
      最近更新 更多