Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I rotate a 2d array in php by 90 degrees

Tags:

arrays

php

matrix

I want to rotate a matrix 90 degrees clockwise. This amounts to making the first column in the input the first row of the output, the second column of the input the 2nd row of the output, and the 3rd column of the input the 3rd row of the output. Note that the bottom of the column=the beginning of the row, because of the 90 degree rotation.

For example:

$matrix=    [[1, 2, 3]
             [4, 5, 6], 
             [7, 8, 9]];

rotate90degrees($matrix)=      [[7, 4, 1],
                                [8, 5, 2],
                                [9, 6, 3]]

What I know is I have first transpose the matrix and then swap the columns to rotate the matrix by 90 degrees. How can this be applied to php?

like image 821
Ahmed Safadi Avatar asked May 06 '15 20:05

Ahmed Safadi


People also ask

How do you rotate a 2d matrix 90 degrees?

Rotate Matrix 90 Degree Clockwise or Right Rotation The rotation of a matrix involves two steps: First, find the transpose of the given matrix. Swap the elements of the first column with the last column (if the matrix is of 3*3). The second column remains the same.

How do you rotate a 45 degree matrix?

The formula of this rotation is : RM[x + y - 1][n - x + y] = M[x][y], where RM means rotated matrix, M the initial matrix, and n the dimension of the initial matrix (which is n x n). So, a32, from the third row and second column will get to the fourth row and the fourth column.


1 Answers

I showed you how to transpose an array in answer to a previous question, to rotate 90 degrees, use that transpose logic, and then reverse the order of the values in each row in turn:

$matrix = [
    [1, 2, 3],
    [4, 5, 6], 
    [7, 8, 9],
];

array_unshift($matrix, null);
$matrix = call_user_func_array('array_map', $matrix);
$matrix = array_map('array_reverse', $matrix);
var_dump($matrix);

Demo

like image 142
Mark Baker Avatar answered Sep 21 '22 21:09

Mark Baker