需要的公式:将数组排序到数组 - “蜿蜒”

时间:2010-03-17 17:36:12

标签: algorithm arrays sorting

在你们最后一次如此优雅地帮助我之后,这是另一个棘手的阵列分拣机。

我有以下数组:

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]

我将它用于一些视觉效果并像这样呈现:

1   2  3  4

5   6  7  8

9  10 11 12

13 14 15 16

现在我想要将数组排序为稍后有一条“蛇”:

// rearrange the array according to this schema
1   2  3 4

12 13 14 5

11 16 15 6

10  9  8 7

// the original array should look like this
a = [1,2,3,4,12,13,14,5,11,16,15,6,10,9,8,7]

现在我正在寻找智能公式/智能循环来做到这一点

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++;
}

再次感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我很无聊,所以我在循环中用9行代码为你制作了一个python版本。

ticker = 0
rows = 4
cols = 4
originalArray = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
newArray = [None] * (rows * cols)
row = 0
col = 0
dir_x = 1
dir_y = 0
taken = {}

while (ticker < len(originalArray)):
    newArray[row * cols + col] = originalArray[ticker]
    taken[row * cols + col] = True

    if col + dir_x >= cols or row + dir_y >= rows or col + dir_x < 0:
        dir_x, dir_y = -dir_y, dir_x
    elif ((row + dir_y) * cols + col + dir_x) in taken:
        dir_x, dir_y = -dir_y, dir_x

    row += dir_y
    col += dir_x    
    ticker += 1

print newArray

答案 1 :(得分:0)

如果你记得

,你可以直接索引蛇形线圈
1 + 2 + 3 + ... + n = n*(n+1)/2
m^2 + m - k = 0  =>  m - (-1+sqrt(1+4*k))/2

并查看线圈的图案。 (我将暂时留下它作为暗示 - 您也可以使用n^2 = (n-1)^2 + (2*n+1)反向索引或其他各种方法来解决问题。)

在翻译代码时,如果您只想填写矩阵,那么它实际上并不比Tuomas的解决方案短。