Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Using ArrayIterator
- */
- class Matrix
- {
- private $matrix = [];
- private $n = 0;
- public function __construct($n)
- {
- $this->n = $n;
- $index = 1;
- for ($row = 1; $row <= $n; $row++) {
- $currRow = [];
- for ($col = 1; $col <= $n; $col++) {
- $currRow[] = $index;
- $index++;
- }
- $this->matrix[] = $currRow;
- }
- }
- public function rotate()
- {
- $revArr = array_reverse($this->matrix);
- $rotated = [];
- for ($i = 0; $i < $this->n; $i++) {
- $iter = new ArrayIterator($revArr);
- $temp = [];
- while ($iter->valid()) {
- $temp[] = $iter->current()[$i];
- $iter->next();
- }
- $rotated[] = $temp;
- }
- $this->matrix = $rotated;
- }
- public function render()
- {
- foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($this->matrix)) as $k => $v) {
- echo $v;
- echo $k === $this->n - 1 ? '<br />' : ' ';
- }
- }
- }
- // Initial matrix
- $matrix = new Matrix(3);
- $matrix->render();
- echo '<br />';
- // One rotation
- $matrix->rotate();
- $matrix->render();
- echo '<br/>';
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement