algorithm - 所需公式 : Sort array to array -"snaked"

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

再次感谢您的帮助。

最佳答案

我很无聊,所以我给你做了一个 python 版本,循环中有 9 行代码。

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

关于algorithm - 所需公式 : Sort array to array -"snaked",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2464469/

相关文章:

algorithm - 数组中的最大绝对差

algorithm - 为什么说深度优先搜索会遇到无限循环?

c# - 用霍纳方案简化算法

arrays - 反转数组中键、值的顺序转换为哈希

c - 在 C 中将 double 存储在数组中

javascript - JavaScript 中的洪水填充算法 - 太多递归

c++ - 如何在使用for循环和数组时更改为c代码

sorting - Solr 合并日期字段进行排序

c - 数组的选择排序结构问题

python - 如何正确排序带有数字的字符串?