此函数采用数组: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);
}
});
答案 0 :(得分:0)
使用您的逻辑,它为添加结果而添加的索引始终是切片数组的第一个和最后一个元素。
console.log(ary[0] + ',' + ary[finalDiffs.length -1])
返回findLowest
之前。