在你们上次如此优雅地帮助我之后,这里有另一个棘手的数组排序器。
我有以下数组:
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/