使用数组打印蛇图案

问题描述 投票:0回答:5

我在执行任务时遇到问题,我们需要打印出这个数组:

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

我的代码有些正确,但它没有打印

10
19
应该在的地方。

我的输出:

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
5个回答
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  
    }
}

说明:

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

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    

0
投票

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

它可以用三元来简化,但这使它更具可读性

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

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

0
投票

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

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

0
投票

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

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. 该模式以
    start
    值为
    1
    开始。
  2. 当主循环计数器为偶数时,为数组赋值的计数器从
    start
    值开始,增加 1,
    LEN
    倍。最后,它设置
    start
    为下一行以
    final_value_of_the_array_value_assignment_counter - 1 + LEN
    开头。
  3. 当主循环计数器为奇数时,为数组赋值的计数器从
    start
    值开始,并减少 1
    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  

0
投票

哈哈,抱歉,迟到了,但我认为你只需要做 i >= 0 而不是 i > 0。

© www.soinside.com 2019 - 2024. All rights reserved.