LucasMelo
LucasMelo

Reputation: 117

Matrix manipulation (rotation/rolling)

I have this 3x3 matrix:

{
 [1,2,3],
 [4,5,6],
 [7,8,9]
}

Suppose that if I send two parameters m and n, this matrix must move m and n positions (m positive / move right or negative move left) and (n positive / move down or n negative move up). For the sample if I send m = 1 , n = 0:

{
 [3, 1, 2],
 [6, 4, 5],
 [9, 7, 8]
}

Is there some kind of method to do this? Or is it just 'hard handwork'?

Upvotes: 1

Views: 98

Answers (1)

OldCurmudgeon
OldCurmudgeon

Reputation: 65813

If you are prepared to use List<List<Integer>> instead of int[][] you can use Collections.rotate(List list,int distance).

private void rotate(List<List<Integer>> matrix, int m, int n) {
    for (List<Integer> row : matrix) {
        Collections.rotate(row, m);
    }
    Collections.rotate(matrix, n);
}

public void test() {
    int[][] m = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    List<List<Integer>> matrix = new ArrayList<>();
    for (int[] r : m) {
        List<Integer> row = new ArrayList<>();
        for (int v : r) {
            row.add(v);
        }
        matrix.add(row);
    }
    System.out.println("Before: " + matrix);
    rotate(matrix, 1, 2);
    System.out.println("After: " + matrix);
}

Prints:

Before: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

After: [[3, 1, 2], [6, 4, 5], [9, 7, 8]]

which is slightly different from what you were expecting but it looks like it makes sense.

Upvotes: 2

Related Questions