假设您在给定域中有一组数字,例如:[-4,4]
还假设这组数字位于一个数组中,并且按数字顺序排列,如下所示:
[-4, -3 -2, -1, 0, 1, 2, 3, 4]
现在假设我想为这组数字创建一个新的零点,如下所示:(我选择-2作为我的新轴,并且所有元素都会相应移动)
Original: [-4, -3 -2, -1, 0, 1, 2, 3, 4]
Zeroed: [-2, -1 0, 1, 2, 3, 4, -4, -3]
使用新的归零数组,假设我有一个名为的函数:
"int getElementRelativeToZeroPosition(int zeroPos, int valueFromOriginalArray, int startDomain, int endDomain) {...}"
示例用法:
I am given 3 of the original array, and would like to see where it mapped to on the zeroed array, with the zero on -2.
getElementRelativeToZeroPosition(-2, 3, -4, 4) = -4
无需创建任何数组并为此映射移动元素,我将如何以数学方式生成上述函数的所需结果?
最佳答案
我会这样做:
- 获取原零位置索引
- 获取新零位置的索引(即示例中的 -2 索引)
- 获取搜索位置的索引(索引为 3)
- 计算新零位置和原始零位置之间的移动 vector
- 将移动 vector 应用于搜索位置取模数组大小以执行旋转
假设您的数组是从零开始的:
index(0) => 4
index(-2) => 2
index(3) => 7
array_size => 9
move_vector => index(0) - index(-2)
=> 4 - 2 => +2
new_pos(3) => (index(3) + move_vector) modulo array_size
=> (7 + 2) mod 9 => 0
value_at(0) => -4
就是这样
关于c++ - 以数学方式旋转有序数字数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37682309/