【发布时间】:2019-03-11 21:25:43
【问题描述】:
我希望有人可以帮助解决一个涉及以“循环”方式查找数组的正确值的小算法问题。我的例子是 javascript,虽然理论上它可以是任何语言。
这是场景:我有一个数字数组,以及一个“当前指针”,它是数组的某个索引值。我想传入一个“差异”整数值,它可能是正数或负数。如果 diff 为负,则指针索引减小,循环回到数组的另一侧。如果为正,则指针索引增加,如果超出范围,则循环回数组的另一端。
我在下面包含了一些示例调用,以指示示例函数调用和预期输出。
var arr = [0, 1, 2, 3, 4];
// starting at current index, increase or
// decrease index of arr by "diff" amount
// and then return the value at that index
function getValue(arr, current, diff) {
var newIndex;
if ( diff >= 0 ) {
// increase current value by diff
// increments, in a circular fashion
}
else if ( diff < 0 ) {
// decrease current value by diff
// increments, in a circular fashion
}
return arr[newIndex];
}
// sample calls, with expected output
getValue(arr, 0, 2); // 2
getValue(arr, 0, 4); // 4
getValue(arr, 0, 5); // 0
getValue(arr, 0, 12); // 2
getValue(arr, 0, -1); // 4
getValue(arr, 0, -7); // 3
getValue(arr, 3, 2); // 0
getValue(arr, 3, 4); // 2
getValue(arr, 3, 5); // 3
getValue(arr, 3, 12); // 0
getValue(arr, 3, -1); // 2
getValue(arr, 3, -7); // 1
【问题讨论】:
标签: javascript arrays indexing