Advertisement
Guest User

SoftUni Chalange | RotateMatrix | OOP

a guest
Apr 13th, 2015
312
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.21 KB | None | 0 0
  1. <?php
  2. /**
  3. * Object-oriented
  4. */
  5.  
  6. class Matrix
  7. {
  8.     private $matrix = [];
  9.     private $n = 0;
  10.  
  11.     public function __construct($n)
  12.     {
  13.         $this->n = $n;
  14.         $index = 1;
  15.         for ($row = 1; $row <= $n; $row++) {
  16.             $currRow = [];
  17.             for ($col = 1; $col <= $n; $col++) {
  18.                 $currRow[] = $index;
  19.                 $index++;
  20.             }
  21.             $this->matrix[] = $currRow;
  22.         }
  23.     }
  24.  
  25.     public function rotate()
  26.     {
  27.         $result = [];
  28.  
  29.         for ($col = 0; $col < $this->n; $col++) {
  30.             $currRow = [];
  31.             for ($row = $this->n - 1; $row >= 0; $row--) {
  32.                 $currRow[] = $this->matrix[$row][$col];
  33.             }
  34.             $result[] = $currRow;
  35.         }
  36.  
  37.         $this->matrix = $result;
  38.     }
  39.  
  40.     public function render()
  41.     {
  42.         for ($row = 0; $row < $this->n; $row++) {
  43.             for ($col = 0; $col < $this->n; $col++) {
  44.                 echo $this->matrix[$row][$col] . ' ';
  45.             }
  46.             echo '<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