12
votes

Tourner le tableau dans le sens des aiguilles d'une montre

J'ai un tableau de deux dimensions que j'ai besoin de faire pivoter de 90 degrés dans le sens des aiguilles d'une montre, mais je continue à obtenir ArrayIndexOUPOfbounds ...

public int[][] rotateArray(int[][] arr) {
    // first change the dimensions vertical length
    // for horizontal length and vice versa
    int[][] newArray = new int[arr[0].length][arr.length];

    // invert values 90 degrees clockwise by starting
    // from button of array to top and from left to right
    int ii = 0;
    int jj = 0;
    for (int i = 0; i < arr[0].length; i++) {
        for (int j = arr.length - 1; j >= 0; j--) {
            newArray[ii][jj] = arr[i][j];
            jj++;
        }
        ii++;
    }
    return newArray;
}


2 commentaires

Ce n'est pas une rotation de matrice. C'est une transposition matricielle en.wikipedia.org/wiki/transpose qui est une réflexion sur le principal diagonale.


Cela vient de renverser les lignes, mais JJ doit être réglé à 0 pour chaque i. Pour faire pivoter Exchange I avec J en arr [I] [J] (et n'oubliez pas de définir JJ à 0


10 Réponses :


3
votes

jj ++ est exécuté i * j fois, et cela ne peut pas être bon du tout.

Essayez de réinitialiser jj dans la boucle extérieure.


0 commentaires

16
votes

Je ne comprends pas la logique de vos boucles - ne devrait-il pas être xxx

net de savoir si chaque index monte, comme i ici, ou Down, comme j ici (et de savoir si ou les deux doivent être "retournés" dans l'affectation, par exemple en utilisant arr.length-1-j au lieu de plaine < Code> j sur un côté du = dans l'affectation ;-), puisque arr compte Les dimensions sont arr.length par par < Code> Arr [0] .length , et vice versa pour Newarray , il me semble que le premier index sur Arr (deuxième sur Newarray ) doit être celui qui s'étend sur la plage de 0 à arr.length-1 inclus, et l'autre plage de l'autre index.

C'est une sorte de "Analyse dimensionnelle de base" (sauf que la "dimension" est utilisée dans un sens différent de celui qui va normalement avec "analyse dimensionnelle" qui fait référence aux dimensions physiques, c'est-à-dire, temps, masse, longueur et c ;-). La question de "basculement" et que chaque boucle augmente ou diminue dépend de la visualisation exactement ce que vous voulez dire et que je ne suis pas le plus grand "visualiseur mental", donc je pense, dans la vie réelle, j'essayais les différentes variantes de cette " transposition de l'axe "jusqu'à ce que je frappe celui qui est signifié; -).


3 commentaires

@user, vous êtes la bienvenue - je me suis soupçonné que j'avais manqué à basculement et / ou à l'envers contre les indices (ou les deux? -), comme je l'ai mentionné dans le 2e paragraphe ;-).


Newarray [i] [j] = arr [j] [i]; transpose la matrice. Il devrait être NewArray [i] [longueur-1-j] = arr [j] [i];


@Maciej est correct. Voir ma réponse pour un traitement plus approfondi du problème.



41
votes

Voici une matrice standard Code de rotation des aiguilles d'une montre: XXX

Notez quelques éléments:


1 commentaires

Comment puis-je l'allumer dans le sens anti-horaire



0
votes
public class RotateMatrix {

    static int index_of_rows;
    static int index_of_columns;
    static int number_of_rows;
    static int number_of_columns;

    public static void main(String[] args) {
        int[][] matrix={{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}};
        index_of_rows = matrix.length -1;
        index_of_columns = matrix[0].length -1;
        number_of_rows = matrix.length;
        number_of_columns = matrix[0].length;


        RotateMatrix rm = new RotateMatrix();

        rm.printGrid(matrix);//before rotation
        rm.rotate360CW(matrix,rm);

    }

    public int[][] rotate90CW(int[][] matrix, RotateMatrix rm) {

        int[][] newMatrix = new int[number_of_rows][number_of_columns];
        int totalNumber = (number_of_rows) * (number_of_columns);
        int[] intArray = createSingleArray(matrix,totalNumber);


        int a =0;
            // kept index from out-of-bounds error; mod to:
            // number_of_columns-1
            // number_of_rows-1
        for(int c=number_of_columns-1; c>=0; c--) {
            for(int r=0; r<=number_of_rows-1; r++) {
                newMatrix[r][c] = intArray[a];
                a++;
            }
        }
        rm.printGrid(newMatrix);
        return newMatrix;
    }

    public int[] createSingleArray(int[][] matrix, int totalNumber) {
        int a=0;
        int[] intArray = new int[totalNumber];

        for(int b=0;b<=index_of_rows; b++) {
            for(int c=0; c<=index_of_columns;c++) {
                intArray[a] = matrix[b][c];
                a++;
            }
        }
        return intArray;
    }

    public void printGrid(int[][] matrix) {
        StringBuilder sb = new StringBuilder("--------------------------");

        for(int i =0; i<=index_of_rows; i++) {
            System.out.println(sb.toString());//print each row
            sb.delete(0, sb.length());//Then clear the row and build the next
            for(int j=0; j<=index_of_columns;j++) {
                sb.append(matrix[i][j]+",");
            }
        }
        System.out.println(sb.toString());

    }

    public int[][] rotate180CW(int[][] matrix, RotateMatrix rm) {
        return rm.rotate90CW(rm.rotate90CW(matrix, rm), rm);
    }

    public int[][] rotate270CW(int[][] matrix, RotateMatrix rm) {
        return rm.rotate90CW(rm.rotate90CW(rm.rotate90CW(matrix, rm), rm),rm);
    }

    public int[][] rotate360CW(int[][] matrix, RotateMatrix rm) {
        return rm.rotate90CW(rm.rotate90CW(rm.rotate90CW(rm.rotate90CW(matrix, rm),
                                                    rm),rm),rm);
    }
}

0 commentaires

-2
votes
public class Sample {

    /**
     * @param args
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub      
        int mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }, { 10, 11, 12 } };
        printMatrix(mat);

        int antiClockwiseMatrix[][] = rotateAntiClockwiseMatrix(mat);
        printMatrix(antiClockwiseMatrix);
        int clockwiseMatrix[][] = rotateClockwiseMatrix(mat);
        printMatrix(clockwiseMatrix);

        // rotateAntiMatrix(mat);
    }

    public static void printMatrix(int mat[][]) {
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[0].length; j++) {
                System.out.print(mat[i][j] + "\t");
            }
            System.out.print("\n");
        }
        System.out.print("\n");

    }

    static public int[][] rotateAntiClockwiseMatrix(int mat[][]) {
        int rows = mat.length;
        int cols = mat[0].length;
        int newMat[][] = new int[cols][rows];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                newMat[j][i] = mat[i][j];
            }
        }

        return newMat;
    }

    static public int[][] rotateClockwiseMatrix(int mat[][]) {
        int newMat[][] = rotateAntiClockwiseMatrix(mat);
        int finMat[][] = new int[newMat.length][newMat[0].length];
        for (int i = 0; i < newMat.length; i++) {
            int n = 0;
            for (int j = newMat[0].length - 1; j >= 0; j--) {
                finMat[i][n] = newMat[i][j];
                n++;
            }
        }

        return finMat;

    }
}

1 commentaires

Logique très simple pour faire pivoter la matrice dans le sens des aiguilles d'une montre ou dans le sens anti-horaire



1
votes

solution pour les objets génériques: xxx

utilisation: xxx


0 commentaires

0
votes

étapes pour faire pivoter une matrice dans le sens des aiguilles d'une montre ou dans le sens aigu des aiguilles d'une montre:

  1. prenez la transposition de la matrice donnée li>
  2. Swap colonnes verticales (si vous voulez une rotation dans le sens des aiguilles d'une montre) (Ou) li> ol>

    colonnes d'échange horizontal (si vous voulez une rotation anti-horaire) p>

    programme pour la rotation dans le sens des aiguilles d'une montre: p>

    //Anti-Clockwise Rotation
    import java.util.Scanner;
    
    public class Anti_ClockWiseRotation {
        public static void main(String[] args) {
            int i, j, sw, n = 6;
            int a[][] = new int[6][6];
            int b[][] = new int[6][6];
            System.out.println("Enter the  elements for matrix\n");
            Scanner input = new Scanner(System.in);
            for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                    a[i][j] = input.nextInt();
                }
            }
            System.out.println("The Matrix\n");
            for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                    System.out.print(a[i][j] + "\t");
                }
                System.out.println("\n");
            }
            System.out.println("Transformation of given matrix\n");
            for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                    b[i][j] = a[j][i];
                }
            }
            for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                    System.out.print(b[i][j] + "\t");
                }
                System.out.println("\n");
            }
            System.out.println("Anti-Clockwise Rotation of given matrix\n");
            for (i = 0; i < n; i++) {
                for (j = 0; j < n / 2; j++) {
                    sw = b[j][i];
                    b[j][i] = b[n - 1 - j][i];
                    b[n - 1 - j][i] = sw;
                }
                System.out.println("\n");
            }
            for (i = 0; i < n; i++) {
                for (j = 0; j < n; j++) {
                    System.out.print(b[i][j] + "\t");
                }
                System.out.println("\n");
            }
        }
    }
    


0 commentaires

0
votes

Je comprends tout à fait que cette question n'a rien à voir avec Swift, mais voici quelques verbeux Swift 4: xxx

Ce fil ou tout ce qui est apparu quand j'ai cherché pour la question de Swift.


0 commentaires

1
votes
static int[][] rotateClockwise(int[][] matrix) {
    int rowNum = matrix.length;
    int colNum = matrix[0].length;
    int[][] temp = new int[rowNum][colNum];
    for (int i = 0; i < rowNum; i++) {
        for (int j = 0; j < colNum; j++) {
            temp[i][j] = matrix[rowNum - j - 1][i];
        }
    }
    return temp;
}

0 commentaires

0
votes

voici ma solution vérifiée:

public int[][] rotateImage(int[][] a) {
    int colLenght = a[0].length;
    int rowLength = a.length;
    int[][] r = new int[rowLength][colLenght];

    for (int i = 0; i < a.length; i++) {
        for (int j = a.length - 1, rc = 0; j >= 0 && rc < a.length; j--, rc++) {
            r[i][rc] = a[j][i];
        }
    }
    return r;
}


0 commentaires