如何显示在递归函数中添加了哪些变量

How to show what variables are being added in this recursive function

本文关键字:添加 变量 递归函数 何显示 显示      更新时间:2023-09-26

此函数接受一个数组:var data = [5,10,28,50,56,280];,并检查是否可以将任何索引组合在一起以创建一个大于变量的数字:在本例中为30。这个函数工作得很完美,但我想让它显示它为了得到结果而添加的索引。在这种情况下,33将显示28 + 5

var findLowest = function(ary, limit) {
    if (limit < ary[0]) return ary[0];
    // If there's a number in our ary that's higher than the limit,
    // this is the initial benchmark
    var bestCandidate = Infinity,
        maxIndex = ary.findIndex(v => v > limit);
    if (maxIndex !== -1) {
        bestCandidate = ary[maxIndex] - limit;
        ary = ary.slice(0, maxIndex);
    }
    // Calculate remainders, call this method recursively for all remainders
    var diffs = ary.map(v => limit % v);
    var finalDiffs = diffs.map(v => findLowest(ary, v) - v);
    
    return limit + Math.min(bestCandidate, finalDiffs.sort()[0]);
    
};
var prepareData = function(ary) {
    return ary
        // Remove duplicates of nrs in array
        .reduce((res, v) => {
            var needed = !res.length || res.every(r => v % r);
            return needed ? res.concat(v) : res;
        }, [])
        // Generate each combination (length * length - 1)
        .reduce((res, v, i, all) => {
            return res.concat(v).concat(all.slice(i + 1).map(v2 => v + v2));
        }, [])
        
        // Sort lowest first
        .sort((a, b) => a - b);
}
var data = [5,10,28,50,56,280];
var testCases = [
    [data, 30, 0], //<----30 is being tested against the array
];
testCases.forEach(tc => {
    var prep = prepareData(tc[0]);
    var result = findLowest(prep, tc[1]);
    if (result !== tc[2]) {
      document.write("Result: ", result);
    }
});

根据您的逻辑,它所添加的索引将始终是切片数组的第一个和最后一个元素。

console.log(ary[0] + ',' + ary[finalDiffs.length -1])

在返回findLowest之前