gpt4 book ai didi

javascript - 递归返回检查 array[i+1] 和 array[i-1]

转载 作者:行者123 更新时间:2023-12-03 08:57:09 25 4
gpt4 key购买 nike

我正在制作一个时间线,并希望根据发生的重叠次数对“事件”进行分层。

我在堆栈溢出上找到了几个关于如何计算重叠间隔的答案,尽管在我的例子中,我希望当重叠是间接的时计数增加。

我想出了以下递归方法:

countOverlaps: function(i, allItems) {

var currentItem = allItems[i];

// Declare position variables
var currentItemStart = this.getStartTimeMinutes(currentItem.timeStartString);
var currentItemEnd = currentItemStart + currentItem.duration;

var nextItemStart = (i < allItems.length - 1) ? this.getStartTimeMinutes(allItems[i + 1].timeStartString) : null;
var nextItemEnd = (nextItemStart != null) ? nextItemStart + allItems[i + 1].duration : null;

var prevItemStart = (i >= 1) ? this.getStartTimeMinutes(allItems[i - 1].timeStartString) : null;
var prevItemEnd = (prevItemStart != null) ? prevItemStart + allItems[i - 1].duration : null;

// The logic
// If the next item is an overlap, test the next item

// If the previous item is an overlap, test the previous item

if (currentItemEnd > nextItemStart && currentItemStart < nextItemEnd && nextItemStart != null) {
return 1 + this.countOverlaps((i + 1), allItems); // BUT how do I do the same for the previous one?
} else {
return 0;
}

},

但现在我陷入困境了。我认为它按照我想要的方式工作,只是它只是向前计数。如果我想向后和向前检查,每个递归调用不会一次又一次地测试相同的索引吗?

最佳答案

像所有递归一样,您只使用函数中的一个元素/项执行某些操作。请记住终止 - 这是递归中最重要的事情(不,这不是 self 调用,因为没有它,它根本就不是递归)。之后,您将使用另一个修改后的参数来调用自己。

因为我对你的理解是正确的,所以你想从某个地方开始,然后向左向右走多远。查看终止代码。您应该根据需要更改条件。

起始sum left 和 sum right 不是递归的一部分,因为每次递归您只想朝一个方向前进。

此代码很简单,因此您可以轻松地根据需要进行调整。

function sum(index, array){    
function sumRecursion(index, array, direction){
// the termination ;)
if (index < 0) return 0;
if (index > array.length) return 0;

// do some stuff with your array at the current index.
// sorry, I did'nt read your logic code
var count = ...

// now the recursion
return count + sum(index + direction, array, direction);
}
return sumRecursion(index, array, -1) + sumRecursion(index, array, +1);
}

关于javascript - 递归返回检查 array[i+1] 和 array[i-1],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32445014/

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