Safad Funy Safad Funy - 2 months ago 5
PHP Question

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

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?

Answer

php doesn't have concepts like "transpose" for a matrix without adding some sort of linear algebra library. you can do it natively by eaching through the matrix and swapping some indexes

<?php

function rotate90($mat) {
    $height = count($mat);
    $width = count($mat[0]);
    $mat90 = array();

    for ($i = 0; $i < $width; $i++) {
        for ($j = 0; $j < $height; $j++) {
            $mat90[$height - $i - 1][$j] = $mat[$height - $j - 1][$i];
        }
    }

    return $mat90;
}

$mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
print_r($mat);
//123
//456
//789
print_r(rotate90($mat));
//741
//852
//963


$mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9], ["a", "b", "c"]];
print_r($mat);
//123
//456
//789
//abc
print_r(rotate90($mat));
//a741
//b852
//c963
Comments