gpt4 book ai didi

arrays - 需要的公式 : Sort array to array -"zig-zag"

转载 作者:行者123 更新时间:2023-12-04 21:26:29 27 4
gpt4 key购买 nike

我有以下数组:

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

Now I want to sort the array like this to have a "zig-zag" when rendering later.

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

是的,现在我正在寻找一个聪明的公式来做到这一点
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++;
}

最佳答案

查看矩阵的结构:

1    3
| / /
| / /
|/ / ...
2 / 5
/ /
/ /
4

第一行从 1 开始

第二行从 2 = 1 + 1 开始(第一个 zig 中的# 个元素)

第三行从 4 = 1 开始
+ 1(第一个 zig 中的# 个元素)
+ 2 (# 2nd zig 中的元素)

...

第 3 行结束于 6 = 第 3 行开始 + 行号
= 4 + 3 = 7

您可以为 i 推导出闭式公式继续前进。

关于arrays - 需要的公式 : Sort array to array -"zig-zag",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2461863/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com