<?php
$matrix = [[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16],
// [17, 18, 19, 20]
];
$r = 1;
matrixRotation($matrix, $r);
function matrixRotation($matrix, $r) {
$m = new Matrix($matrix);
$m->rotate();
print_r($m->get());
}
class Matrix
{
private $mx;
private $m;
private $n;
private $a; // i [a,b]
private $b;
private $c; // j [c,d]
private $d;
public function get() {
return $this->mx;
}
public function __construct($mx) {
try {
$this->set($mx);
} catch(\Exception $e) {
echo $e->getMessage();
// exit(1);
}
}
private function set(array $mx) {
$this->m = count($mx);
$this->n = count($mx[0]);
$this->a = 0;
$this->b = m-1;
$this->c = 0;
$this->d = n-1;
$this->mx = $mx;
}
public function rotate($r) {
$k = 0;
while(1) {
$this->a += $k;
$this->b -= $k;
$this->c += $k;
$this->d -= $k;
if (
$this->a === $this->b ||
$this->c === $this->d
) {
break;
}
$mult = 2*($this->m-2*$k)+2*($this->n-2*$k)-4;
$rm = $r % $mult;
while($rm--) {
rotateSquare();
}
++$k;
}
}
private function rotateSquare($k) {
$t = []; //transite
for($i=0; $i<$this->m; ++$i) {
for($j=0; $j<$this->n; ++$j) {
$t[$i][$j] = [0,0];
}
}
$j=$this->c;
for($i=$this->a; $i<$this->b; ++$i) {
$t[$i][$j] = [-1,0];
}
$i=$this->b;
for($j=$this->c; $j<$this->d; ++$j) {
$t[$i][$j] = [0,1];
}
$j=$this->d;
for($i=$this->b; $i>$this->a; --$i) {
$t[$i][$j] = [1,0];
}
$i=$this->a;
for($j=$this->d; $j<$this->c; --$j) {
$t[$i][$j] = [0,-1];
}
$temp = [];
for($i=0; $i<$this->m; ++$i) {
for($j=0; $j<$this->n; ++$j) {
$temp[$i + $t[$i][$j][0] ]
[$j + $t[$i][$j][1] ] = $this->mx[$i][$j];
}
}
$this->mx = $this->ksort($temp);
return $this;
}
private function ksort($temp) {
foreach($temp as &$ar){
ksort($ar);
}
ksort($temp);
return $temp;
}
}
preferences:
36.47 ms | 402 KiB | 5 Q