Zig-zag scan an N x N array

前端 未结 8 1397
暗喜
暗喜 2021-01-30 08:40

I have a simple array. The array length always has a square root of an integer. So 16, 25, 36 etc.

$array = array(\'1\', \'2\', \'3\', \'4\' ... \'25\');
         


        
8条回答
  •  长情又很酷
    2021-01-30 09:16

    With a single loop and taking advantage of the simetry and with no sorts:

    function waveSort(array $array) {
        $n2=count($array);
        $n=sqrt($n2);
        if((int)$n != $n) throw new InvalidArgumentException();
    
        $x=0; $y=0; $dir = -1;
    
        $Result = array_fill(0, $n2, null);
        for ($i=0; $i < $n2/2; $i++) {
    
            $p=$y * $n +$x;
    
            $Result[$i]=$array[$p];
            $Result[$n2-1-$i]=$array[$n2-1-$p];
    
            if (($dir==1)&&($y==0)) {
                $x++;
                $dir *= -1;
            } else if (($dir==-1)&&($x==0)) {
                $y++;
                $dir *= -1;
            } else {
                $x += $dir;
                $y -= $dir;
            }
        }
    
        return $Result;
    }
    
    $a = range(1,25);
    var_dump(waveSort($a));
    

提交回复
热议问题