假设我有一个这样的数组:
let arr = [1,2,3....36,38,39]; //an array of 39 elements标题中的“‘looped”是指当向前迭代数组时,迭代从arr[39]跳到arr[0],从arr[0]跳到arr[39]也是如此-本质上,数组是一个闭环。
在我的代码中,我交替迭代的方向,并且每个这样的单步执行的开始和结束索引都是预先确定的:
arr[0] //initial condition is always the same
arr[5]
arr[17]
arr[30]
arr[14]
etc.我的问题是这样的--有没有一种简单的方法来确定哪种迭代方式更“短”,并考虑到arr39和arr之间的差距?
也就是说,当迭代在arr35,下一条指令是转到arr2时,它更接近于通过6步而不是后退33步的“间隙”。
发布于 2019-07-16 11:45:58
使用slice方法来获取两个方向的差异的计数如何?它可能工作得很好,因为你可以使用负数来计算“跳跃间隔”时的项数,我假设你可能是在两个方向上遍历数组,所以你可以从[2] -> [35]或[36] -> [35]这样的东西开始,而不一定总是向前移动。
function shortestPath (idx1, idx2, array) {
const min = Math.min(idx1, idx2);
const max = Math.max(idx1, idx2);
const straight = array.slice(min, max).length;
const looped = array.slice(max - array.length).length + array.slice(0, min).length;
return (straight < looped)
? 'straight' : 'jump the gap';
}
const array = new Array(40);
shortestPath(2, 35, array) // 'jump the gap'
shortestPath(35, 2, array) // 'jump the gap'
shortestPath(36, 35, array) // 'straight'
shortestPath(35, 36, array) // 'straight'我没有任何错误检查或任何东西,如果你给它的索引超过array.length或负数等…但这应该会给你一个开始。它之所以有效,是因为slice允许您使用负数作为开头。所以slice(-2)说把最后两件给我。这样,我们可以抓取两个索引两边的项,然后将它们相加,而不是抓取数组的中间。
发布于 2019-07-16 13:37:28
给定数组的m大小,i和j分别为实际和下一个index,则:
if(Math.abs(i - j) > Math.abs(i - (m + j))) {
// use gap
} else {
// go straight
}你可以把这个间隔看作是紧跟在第一个数组之后的第二个数组。如果是这样,那么下一个索引将是m + j。
https://stackoverflow.com/questions/57049595
复制相似问题