1
votes

Impression d'un motif de serpent à l'aide d'un tableau

J'ai des problèmes avec une affectation où nous devons imprimer ce tableau:

//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

Mon code est quelque peu correct mais il n'imprime pas 10 et 19 là où il devrait être.

Ma sortie:

Choisissez un nombre pour les lignes de 0 à 16.

5

Choisissez un nombre pour les colonnes de 0 à 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

Mon code:

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

Quelqu'un peut-il détecter la cause de l'erreur? Toute aide serait appréciée.


0 commentaires

4 Réponses :


0
votes

Cela générera le motif "serpentin" que vous avez décrit.

Il pourrait être simplifié avec ternaire mais cela le rend plus lisible je pense

Il serait intéressant de trouver une manière plus intelligente de le faire cependant, si quelqu'un trouve un meilleur moyen de commenter

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 commentaires

0
votes

Vous pouvez créer un tel tableau comme suit:

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

Transposition de tableau snake em>:

 1  2  3  4  5
10  9  8  7  6
11 12 13 14 15
20 19 18 17 16
// output
Arrays.stream(snakeArr)
        .map(row -> Arrays.stream(row)
                .mapToObj(e -> String.format("%2d", e))
                .collect(Collectors.joining(" ")))
        .forEach(System.out::println);
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);


0 commentaires

0
votes

Un moyen simple de le faire est de créer un tableau 2D comme indiqué ci-dessous, puis d'imprimer sa transposition.

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  

Il s'agit d'un tableau 2D de la dimension, LEN x LEN , où LEN = 5 .

Le modèle ci-dessus ressemble à ceci:

  1. Le modèle commence par une valeur start de 1 .
  2. Lorsque le compteur de la boucle principale est un nombre pair, le compteur, qui attribue une valeur au tableau, commence par la valeur start et augmente d'une fois, LEN . Enfin, il définit start pour que la ligne suivante commence par final_value_of_the_array_value_assignment_counter - 1 + LEN .
  3. Lorsque le compteur de la boucle principale est un nombre impair, le compteur, qui attribue une valeur au tableau, commence par la valeur start et diminue d'une fois LEN . Enfin, il définit start pour que la ligne suivante commence par start + 1 .

La transposition de la matrice ci-dessus ressemblera à:

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  

En termes de code, nous pouvons l'écrire comme:

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

Sortie:

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  

Remplacez la valeur de LEN par 10 et vous obtiendrez le modèle suivant:

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


0 commentaires

1
votes

Je pense que c'est une bonne alternative et facile à comprendre. Faites un commentaire si vous en avez une version simplifiée.

Code:

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    

Explication:

Considérez la première ligne de 5 x 5 matrice nommée "arr" avec motif serpent:

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

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

Remarque importante: à la première ligne, la première colonne est zéro

The element in the even column is equivalent to (currentColumn * Total_No_Of_columns) + 1;

Example: arra[0][2] = (2 * 5) + 1 = 11;

Maintenant, la matrice restante incrémente ou décrémente la boucle à partir du premier élément de cette colonne.

XXX


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


0 commentaires