gpt4 book ai didi

algorithm - 镜像索引到数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:52:47 25 4
gpt4 key购买 nike

假设我有一个大小为 n 的数组。现在当得到一个可以在 [-n; 范围内的索引 i 时2n-1] 我想按如下方式索引到数组中

enter image description here箭头指示如果 i 低于 0(黄色)或高于 n - 1(蓝色)应返回哪个元素

最佳答案

假设您的可能值数组的长度为 n(在我们的例子中 [0, 1, 2, 3, 4] 的长度为 5)。镜子的整个长度为 2n - 1:

possibleValues = [4, 3, 2, 1, 0, 1, 2, 3, 4]

现在,假设索引 0 处的值数组具有镜像 (0) 的中间位置,您必须使用模运算,公式为

result[v] = possibleValues[((v + n - 1) % 2n - 1)]

现在,由于您的实际数组看起来像 [0, 1, 2, 3, 4],您需要将在可能值处使用的索引转换为对您的实际数组更有帮助的内容:

possibleIndex = ((v + n - 1) % 2n - 1)
if (possibleIndex >= n) actualIndex = possibleIndex - n + 1
else possibleIndex = actualIndex = n = possibleIndex

关于algorithm - 镜像索引到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54486416/

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