公式需要:排序阵列基于阵列"蜿蜒"阵列、公式、QUOT

由网友(牛仔很忙)分享简介:之后,你们帮我出这么优雅地最后一次,这里是另一个棘手的数组排序器给你。After the you guys helped me out so gracefully last time, here is another tricky array sorter for you.我有以下的数组:A = [1,2,3,4,...

之后,你们帮我出这么优雅地最后一次,这里是另一个棘手的数组排序器给你。

After the you guys helped me out so gracefully last time, here is another tricky array sorter for you.

我有以下的数组:

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

我使用它的一些视觉的东西,使得它是这样的:

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

I use it for some visual stuff and render it like this:

1   2  3  4

5   6  7  8

9  10 11 12

13 14 15 16

现在我想将数组排序,有一个蛇后:

Now I want to sort the array to have a "snake" later:


// 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]

现在我正在寻找一个聪明的公式/智能循环来做到这一点。

Now I'm looking for a smart formula / smart loop to do that


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

再次感谢您的帮助。

Thanks again for the help.

推荐答案

我很无聊,所以我与环路内9行code做了一个Python版本给你。

I was bored, so I made a python version for you with 9 lines of code inside the loop.

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
阅读全文

相关推荐

最新文章