carb0nshel1 carb0nshel1 - 1 month ago 11
Javascript Question

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

This function takes an array:

var data = [5,10,28,50,56,280];
and checks to see if it can combine any of the indexes together to create a number larger than a variable:
30
in this case. The function works perfectly but I want it to show the indexes it is adding to get its results. In this case 33 would show
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);
}
});




Answer

With your logic, the indexes it is adding to get its result is always going to be the first and last elements of the sliced array.

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

before you return findLowest.