Advertisement
Guest User

SoftUni Chalange | RotateMatrix | OOP, ArrayIterator

a guest
Apr 14th, 2015
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.28 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * Using ArrayIterator
  5. */
  6.  
  7. class Matrix
  8. {
  9.     private $matrix = [];
  10.     private $n = 0;
  11.  
  12.     public function __construct($n)
  13.     {
  14.         $this->n = $n;
  15.         $index = 1;
  16.         for ($row = 1; $row <= $n; $row++) {
  17.             $currRow = [];
  18.             for ($col = 1; $col <= $n; $col++) {
  19.                 $currRow[] = $index;
  20.                 $index++;
  21.             }
  22.             $this->matrix[] = $currRow;
  23.         }
  24.     }
  25.  
  26.     public function rotate()
  27.     {
  28.         $revArr = array_reverse($this->matrix);
  29.         $rotated = [];
  30.         for ($i = 0; $i < $this->n; $i++) {
  31.             $iter = new ArrayIterator($revArr);
  32.             $temp = [];
  33.             while ($iter->valid()) {
  34.                 $temp[] = $iter->current()[$i];
  35.                 $iter->next();
  36.             }
  37.             $rotated[] = $temp;
  38.         }
  39.         $this->matrix = $rotated;
  40.     }
  41.  
  42.     public function render()
  43.     {
  44.         foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($this->matrix)) as $k => $v) {
  45.             echo $v;
  46.             echo $k === $this->n - 1 ? '<br />' : ' ';
  47.         }
  48.     }
  49.  
  50. }
  51.  
  52. // Initial matrix
  53. $matrix = new Matrix(3);
  54. $matrix->render();
  55. echo '<br />';
  56.  
  57. // One rotation
  58. $matrix->rotate();
  59. $matrix->render();
  60. echo '<br/>';
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement