Rotating a Two-Dimensional Array in Python

Rotating a two-dimensional array in Python

Consider the following two-dimensional list:

original = [[1, 2],
[3, 4]]

Lets break it down step by step:

>>> original[::-1]   # elements of original are reversed
[[3, 4], [1, 2]]

This list is passed into zip() using argument unpacking, so the zip call ends up being the equivalent of this:

zip([3, 4],
[1, 2])
# ^ ^----column 2
# |-------column 1
# returns [(3, 1), (4, 2)], which is a original rotated clockwise

Hopefully the comments make it clear what zip does, it will group elements from each input iterable based on index, or in other words it groups the columns.

How do you rotate a two dimensional array?

Here it is in C#

int[,] array = new int[4,4] {
{ 1,2,3,4 },
{ 5,6,7,8 },
{ 9,0,1,2 },
{ 3,4,5,6 }
};

int[,] rotated = RotateMatrix(array, 4);

static int[,] RotateMatrix(int[,] matrix, int n) {
int[,] ret = new int[n, n];

for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ret[i, j] = matrix[n - j - 1, i];
}
}

return ret;
}

Problem with rotating a two-dimensional array in python

You can use zip on the reversed array:

auxiliaryArray = list(zip(*multiarray[::-1]))

or

auxiliaryArray = list(zip(*reversed(multiarray)))

output: [(7, 4, 1), (8, 5, 2), (9, 6, 3)]

If you need lists and not tuples:

auxiliaryArray = list(map(list, zip(*reversed(multiarray))))

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

How do I rotate a 2-dimensional array in Python or how can I get the result below?

You can try:

>>> A=[[[0, 1, 2], [2, 0, 1], [1, 2, 0]],
... [[1, 0, 2], [0, 2, 1], [2, 1, 0]],
... [[1, 0, 2], [2, 1, 0], [0, 2, 1]]]

>>> transpose_data = map(list, zip(*A))
>>> for data in transpose_data:
... print(data)
...
[[0, 1, 2], [1, 0, 2], [1, 0, 2]]
[[2, 0, 1], [0, 2, 1], [2, 1, 0]]
[[1, 2, 0], [2, 1, 0], [0, 2, 1]]

How do you rotate a two dimensional array?

Here it is in C#

int[,] array = new int[4,4] {
{ 1,2,3,4 },
{ 5,6,7,8 },
{ 9,0,1,2 },
{ 3,4,5,6 }
};

int[,] rotated = RotateMatrix(array, 4);

static int[,] RotateMatrix(int[,] matrix, int n) {
int[,] ret = new int[n, n];

for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
ret[i, j] = matrix[n - j - 1, i];
}
}

return ret;
}


Related Topics



Leave a reply



Submit