Last active
January 4, 2019 20:16
-
-
Save EvilWolf/8ce0b5f82c9c2f431b8a2c8650524bf5 to your computer and use it in GitHub Desktop.
Функция поворота матрицы на 90 градусов
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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