Skip to content

Instantly share code, notes, and snippets.

@EvilWolf EvilWolf/rotateMatrix.php
Last active Jan 4, 2019

Embed
What would you like to do?
Функция поворота матрицы на 90 градусов
<?php
/**
* Пример функции поворота массива
* php version 7.2
*
* @category Algoritms
* @package Array
* @author Evil_Wolf <wolfofdeath@yandex.ru>
* @license MIT https://opensource.org/licenses/MIT
* @link https://ibogatov.ru/
*/
/**
* Функция поврота матрицы на 90 градусов.
*
* @param array $matrix Любая матрица. Хоть 3х3 хоть 5х2
* @param integer $count Кол-во поворотов, отрицательное значение поврачивает в другую сторону
*
* @return array $matrix Возвращает повёрнутую $count раз матрицу.
*/
function rotateMatrix(array $matrix, int $count = 1) : array
{
$rev = $count < 0;
$count = abs($count);
while ($count > 0) {
$sizeX = count($matrix);
$sizeY = count(current($matrix));
$newMatrix = array_fill(0, $sizeY, []);
$newRow = 0;
if ($rev) { // turn -90deg
for ($colKey = $sizeY - 1; $colKey >= 0; $colKey--) {
for ($rowKey = 0; $rowKey < $sizeX; $rowKey++) {
$newMatrix[$newRow][] = $matrix[$rowKey][$colKey];
}
$newRow++;
}
} else { // turn 90deg
for ($colKey = 0; $colKey < $sizeY; $colKey++) {
for ($rowKey = $sizeX - 1; $rowKey >= 0; $rowKey--) {
$newMatrix[$newRow][] = $matrix[$rowKey][$colKey];
}
$newRow++;
}
}
$matrix = $newMatrix;
$count--;
}
return $matrix;
}
/**
* Пример использования
*/
$tetrisShapes = [];
$tetrisShapes['box'] = [['',''],['','']];
$tetrisShapes['line'] = ['','','','',''];
$tetrisShapes['l'] = [['',' '], ['',' '], ['','']];
$tetrisShapes['z'] = [['','',' '], [' ','',' '], [' ','','']];
$tetrisShapes['triangle'] = [[' ','',' '], ['','','']];
$matrix = $tetrisShapes['triangle'];
$rotates = 0;
while ($rotates <= 3) {
$newMatrix = rotateMatrix($matrix, $rotates);
foreach ($newMatrix as $row) {
echo implode(' ', $row) . PHP_EOL;
}
echo PHP_EOL;
$rotates++;
}
/**
* Вывод:
* $ php rotateMatrix.php
* ■
* ■ ■ ■
*
* ■
* ■ ■
* ■
*
* ■ ■ ■
* ■
*
* ■
* ■ ■
* ■
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.