需要的公式:将数组排序到数组 - "zig-zag"

Aro*_*ost 5 language-agnostic arrays sorting

我有以下数组:

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
Run Code Online (Sandbox Code Playgroud)

我用它来做一些这样的视觉效果:

1   2  3  4
5 6 7 8
9 10 11 12
13 14 15 16

现在我想像这样对数组进行排序,以便在稍后渲染时产​​生"锯齿形".

// rearrange the array according to this schema
1  3  6 10

2  5  9 13

4  8 12 15

7 11 14 16

// the original array should look like this:

a = [1,5,2,9,6,3,13,10,7,4,14,11,8,15,12,16]
// the second index to draw should be the first index in the second row,
// which is represent by 5 in the original 1D Array
Run Code Online (Sandbox Code Playgroud)

是的,现在我正在寻找一个聪明的公式来做到这一点

ticker = 0;
rows = 4; // can be n
cols = 4; // can be n
originalArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
newArray = [];

while(ticker < originalArray.length)
{
    //do the magic here
    ticker++;
}
Run Code Online (Sandbox Code Playgroud)

tva*_*son 1

您可以将其按原始顺序排序,只需以不同的方式逐步执行即可。 编辑:事实证明,我的天真的实现没有考虑基于对角线的不同步长。下面的代码确实如此并且已经在 C# 中进行了测试。

 var diagonals = new [] { 1, 2, 3, 4, 4, 3, 2, 1 };
 for (int i = 0, m = 0; m < 4; i = i + m, ++m) {
     for (int j = m, k = 0; k < 4; j = j + diagonals[m+k+1], ++k) {
          Console.Write( i+j+1  );
          Console.Write( " " );
     }
    Console.WriteLine();
 }
Run Code Online (Sandbox Code Playgroud)

显然,如果您需要保持该顺序,则可以使用此算法来填充新数组。它还应该可以扩展——您只需将终止条件更改为数组大小的平方根并自动生成对角线。