Z形扫描一个N×N个阵列阵列

2023-09-12 21:19:00 作者:无欲无求

我有一个简单的数组。数组长度总是具有整数的平方根。因此,16,25,36等。

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');

我要做的,就是安排与HTML数组,使它看起来像,甚至双方的块。

What I do, is arrange the array with HTML so that it looks like a block with even sides.

我想要做的,就是排序的元素,所以,当我通过JSON EN codeD数组jQuery的,它会遍历数组,淡入当前块,所以我会得到一种波动画。所以我想给数组排序有点像这样

What I want to do, is sort the elements, so that when I pass the JSON encoded array to jQuery, it will iterate the array, fade in the current block, and so I'd get a sort of wave animation. So I'd like to sort the array kind of like this

所以,我的排序数组看起来像

So my sorted array would look like

$sorted = array('1', '6', '2', '3', '7', '11', '16, '12' .. '25');

有没有办法做到这一点?..谢谢

Is there way to do so?.. Thanks

推荐答案

下面是我的。

function waveSort(array $array) {
  $dimension = pow(count($array),0.5);
  if((int)$dimension != $dimension) {
    throw new InvalidArgumentException();
  }

  $tempArray = array();
  for($i = 0; $i < $dimension; $i++) {
    $tempArray[] = array_slice($array,$i*$dimension,$dimension);
  }

  $returnArray = array();

  for($i = 0; $i < $dimension * 2 -1; $i++) {
    $diagonal = array();

    foreach($tempArray as $x => $innerArray) {
      if($i - $x >= 0 && $i - $x < $dimension) {
        $diagonal[] = $innerArray[$i - $x];
      }
    }

    if($i % 2 == 1) {
      krsort($diagonal);
    }

    $returnArray = array_merge($returnArray,$diagonal);

  }

  return $returnArray;

}

用法:

<?php
$a = range(1,25);
var_dump(waveSort($a));

输出

array(25) {
  [0]=>
  int(1)
  [1]=>
  int(6)
  [2]=>
  int(2)
  [3]=>
  int(3)
  [4]=>
  int(7)
  [5]=>
  int(11)
  [6]=>
  int(16)
  [7]=>
  int(12)
  [8]=>
  int(8)
  [9]=>
  int(4)
  [10]=>
  int(5)
  [11]=>
  int(9)
  [12]=>
  int(13)
  [13]=>
  int(17)
  [14]=>
  int(21)
  [15]=>
  int(22)
  [16]=>
  int(18)
  [17]=>
  int(14)
  [18]=>
  int(10)
  [19]=>
  int(15)
  [20]=>
  int(19)
  [21]=>
  int(23)
  [22]=>
  int(24)
  [23]=>
  int(20)
  [24]=>
  int(25)
}