【问题标题】:Printing a snake pattern using an array使用数组打印蛇形图案
【发布时间】:2020-04-11 01:02:42
【问题描述】:

我在处理需要打印此数组的作业时遇到问题:

1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25

我的代码有些正确,但它没有在应有的位置打印 1019

我的输出:

Choose a number for the rows from 0 to 16.
5
Choose a number for the columns from 0 to 16
5
1  0  10  0   19
2  9  11  18  20
3  8  12  17  21
4  7  13  16  22
5  6  14  15  23

我的代码:

//snake move with the number
import java.util.Scanner;

public class SnakeMove {
    public static void main(String[] args) {
        //create Scanner object
        Scanner inScan = new Scanner(System.in);

        //prompt the user to choose number for the Row from 0 to 16
        System.out.println("Choose a number for the rows from 0 to 16.");

        //take the input from user with nextInt() method
        //use the variable int row
        int row = inScan.nextInt();

        //prompt the user to choose number for the Col from 0 to 16
        System.out.println("Choose a number for the columns from 0 to 16");

        //take the input from user with nextInt()
        //use the variable int col
        int col = inScan.nextInt();
        if (row != col) {
            System.out.println("Run the program again and choose the same number for Row and Col");
            System.exit(0);
        }
        int[][] arr = move(row, col);
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length; j++) {
                System.out.print(arr[i][j] + "  ");
            }
            System.out.println();
        }
    }//main method

    static int[][] move(int row, int col) {
        boolean flag = true;
        int count = 1;
        int[][] array = new int[row][col];
        for (int j = 0; j < array[0].length; j++) {
            if (flag) {
                for (int i = 0; i < array.length; i++) {
                    //assign the increment value of count
                    // to specific array cells
                    array[i][j] = count;
                    count++;
                }
                flag = false;
            } else {
                //row decrement going up
                for (int i = array.length - 1; i > 0; i--) {
                    //assign the increment value of count
                    // to specific array cells
                    array[i][j] = count;
                    count++;
                }
                flag = true;
            }
        }//column increment
        return array;
    }//move method
}//end SnakeMove class

任何人都可以检测出导致错误的原因吗?任何帮助将不胜感激。

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    我相信这是一个很好的选择并且易于理解。如果您有相同的简化版本,请发表评论。

    代码:

    import java.util.Arrays;
    import java.util.Scanner;
    
    public class SnakePatternProblem {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);   // *INPUT*
            int row = scanner.nextInt();
            int col = scanner.nextInt();
            int[][] array = new int[row][col];
            
            // Initializing first row of the array with a generalized expression
    
            for (int i = 0; i < col; i++) {
                if (i % 2 != 0) array[0][i] = col * (i+1); 
                else array[0][i] = (col * i) + 1;
            }
            
            array[0][0] = 1; // this element is not covered in the above loop.
             
            
           // Nested loop for incrementing and decrementing as per the first row of elements.
    
            for (int i= 1; i< row; i++){
                for (int j=0; j< col; j++){
                    if(j%2==0) array[i][j] = array[i-1][j] + 1;
                else array[i][j] = array[i-1][j] - 1;
                }
            }
            System.out.println(Arrays.deepToString(array));    // *OUTPUT  
        }
    }
    

    解释:

    考虑 5 x 5 矩阵的第一行名为“arr”的蛇形图案:

    1 10 11 20 21
    
    The element in the odd column is equivalent to ((currentColumn + 1) * Total_No_Of_columns);
    
    Example: arr[0][1] = (1 + 1)* 5 = 10
    

    The element in the even column is equivalent to (currentColumn * Total_No_Of_columns) + 1;
    
    Example: arra[0][2] = (2 * 5) + 1 = 11;
    

    重要提示:元素在第一行,第一列为零

     arr[0][0] = 1    -> must be declared
    

    现在,剩余的矩阵从该列的第一个元素开始递增或递减循环。

    Elements with even column number gets incremented by 1 in each row from the first element of that column.
    
     1  -> First element of column-0
     2  -> (1 + 1)
     3  -> (2 + 1).... so on
     4 
     5
    

    Elements with odd column number gets decremented by 1 in each row from the first element of that column. 
    
     10  -> First element of column - 1
     9   -> (10 - 1)
     8   -> (9 - 1).... so on  
     7      
     6    
    

    【讨论】:

      【解决方案2】:

      这将生成您描述的“蛇形”模式。

      可以用三进制来简化,但我认为这使它更具可读性

      如果有人找到更好的方法请评论一下,找到一个更聪明的方法会很有趣

      public static int[][] genArray(int length) {
          int[][] arr = new int[length][length];
      
          int counter = 0;
          for (int col = 0; col < arr.length; col++) {
              if (col % 2 == 0) {
                  for (int row = 0; row < arr.length; row++) {
                      arr[row][col] = counter++;
                  }
              } else {
                  for (int row = arr.length - 1; row >= 0; row--) {
                      System.out.println("row: " + row + ", col: " + col);
                          arr[row][col] = counter++;
                      }
                  }
              }
          }
          return arr;
      }
      

      【讨论】:

        【解决方案3】:

        您可以按如下方式创建这样的数组:

        int m = 5;
        int n = 4;
        int[][] snakeArr = IntStream.range(0, n)
                .mapToObj(i -> IntStream.range(0, m)
                        // even row - straight order,
                        // odd row - reverse order
                        .map(j -> (i % 2 == 0 ? j : m - j - 1) + i * m + 1)
                        .toArray())
                .toArray(int[][]::new);
        
        // output
        Arrays.stream(snakeArr)
                .map(row -> Arrays.stream(row)
                        .mapToObj(e -> String.format("%2d", e))
                        .collect(Collectors.joining(" ")))
                .forEach(System.out::println);
        
         1  2  3  4  5
        10  9  8  7  6
        11 12 13 14 15
        20 19 18 17 16
        

        转置蛇数组

        int[][] transposedSA = new int[m][n];
        IntStream.range(0, m).forEach(i ->
                IntStream.range(0, n).forEach(j ->
                        transposedSA[i][j] = snakeArr[j][i]));
        
        // output
        Arrays.stream(transposedSA)
                .map(row -> Arrays.stream(row)
                        .mapToObj(e -> String.format("%2d", e))
                        .collect(Collectors.joining(" ")))
                .forEach(System.out::println);
        
         1 10 11 20
         2  9 12 19
         3  8 13 18
         4  7 14 17
         5  6 15 16
        

        【讨论】:

          【解决方案4】:

          一个简单的方法是创建一个如下所示的二维数组,然后打印它的转置。

          1   2   3   4   5
          10  9   8   7   6
          11  12  13  14  15
          20  19  18  17  16
          21  22  23  24  25
          

          它是维度为LEN x LEN 的二维数组,其中LEN = 5

          上面的模式是这样的:

          1. 模式以start1 开头。
          2. 当主循环计数器为偶数时,为数组赋值的计数器从start 值开始,并以LEN 倍递增。最后,它将start 设置为下一行以final_value_of_the_array_value_assignment_counter - 1 + LEN 开头。
          3. 当主循环计数器为奇数时,为数组赋值的计数器以start 值开始,并减一LEN 倍。最后,它将start 设置为下一行以start + 1 开头。

          上述矩阵的转置如下:

          1   10  11  20  21  
          2   9   12  19  22  
          3   8   13  18  23  
          4   7   14  17  24  
          5   6   15  16  25  
          

          在代码方面,我们可以写成:

          public class Main {
              public static void main(String[] args) {
                  final int LEN = 5;
                  int[][] arr = new int[LEN][LEN];
                  int start = 1, j, k, col;
                  for (int i = 0; i < LEN; i++) {
                      if (i % 2 == 0) {
                          k = 1;
                          for (j = start, col = 0; k <= LEN; j++, k++, col++) {
                              arr[i][col] = j;
                          }
                          start = j - 1 + LEN;
                      } else {
                          k = 1;
                          for (j = start, col = 0; k <= LEN; j--, k++, col++) {
                              arr[i][col] = j;
                          }
                          start++;
                      }
          
                  }
          
                  // Print the transpose of the matrix
                  for (int r = 0; r < LEN; r++) {
                      for (int c = 0; c < LEN; c++) {
                          System.out.print(arr[c][r] + "\t");
                      }
                      System.out.println();
                  }
              }
          }
          

          输出:

          1   10  11  20  21  
          2   9   12  19  22  
          3   8   13  18  23  
          4   7   14  17  24  
          5   6   15  16  25  
          

          LEN的值改为10,你会得到如下模式:

          1   20  21  40  41  60  61  80  81  100 
          2   19  22  39  42  59  62  79  82  99  
          3   18  23  38  43  58  63  78  83  98  
          4   17  24  37  44  57  64  77  84  97  
          5   16  25  36  45  56  65  76  85  96  
          6   15  26  35  46  55  66  75  86  95  
          7   14  27  34  47  54  67  74  87  94  
          8   13  28  33  48  53  68  73  88  93  
          9   12  29  32  49  52  69  72  89  92  
          10  11  30  31  50  51  70  71  90  91  
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-12-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多