Skip to content

Instantly share code, notes, and snippets.

@everdimension
Created January 18, 2018 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save everdimension/cb74add4de5708363a2593832a709ec3 to your computer and use it in GitHub Desktop.
Save everdimension/cb74add4de5708363a2593832a709ec3 to your computer and use it in GitHub Desktop.
A function that finds all combinations of numbers in an array the sum of which equals a certain number
function arraySum(arr) {
return arr.reduce((sum, next) => sum + next, 0);
}
function padLeft(string, size) {
let res = string;
while (res.length < size) {
res = `0${res}`;
}
return res;
}
function turnIntoIndexes(binaryString) {
return binaryString
.split('')
.map((n, index) => (n === '1' ? index : null))
.filter(Number.isInteger);
}
function getAllCombinations(arr) {
const combinations = [];
const max = 2 ** arr.length;
let n = 0;
while (++n < max) {
const binaryString = n.toString(2);
const visualPosition = padLeft(binaryString, arr.length);
const indexes = turnIntoIndexes(visualPosition);
const combination = indexes.map(i => arr[i]);
combinations.push(combination);
}
return combinations;
}
function sumOfCombinations(values, desiredSum = 10) {
const combinations = getAllCombinations(values);
return combinations.filter(
combination => arraySum(combination) === desiredSum,
);
}
module.exports = {
arraySum,
sumOfCombinations,
};
const assert = require('assert');
const { arraySum, sumOfCombinations } = require('./sumOfCombinations');
/** test arraySum */
assert.equal(arraySum([1, 2, 3]), 6, '1 + 2 + 3 equals 6');
assert.equal(arraySum([97, 1, 1, 1]), 100, '97 + 1 + 1 + 1 equals 100');
/** test sumOfCombinations */
const sum = 10;
const res1 = sumOfCombinations([1, 2, 3, 4, 5], sum);
assert.equal(res1.length, 3, "should've found 3 combinations");
assert.ok(
res1.every(combination => arraySum(combination) === sum),
'Sum of every combination should be correct',
);
const res2 = sumOfCombinations([1, 2, 3, 4, 5, 13, 45, 9, 7, 8], sum);
assert.equal(res2.length, 7, "should've found 7 combinations");
assert.ok(
res2.every(combination => arraySum(combination) === sum),
'Sum of every combination should be correct',
);
const res3 = sumOfCombinations([1, 1, 1, 1, 1, 1, 1, 1, 1, 1], sum);
assert.equal(res3.length, 1, "should've found 1 combination");
assert.ok(
res3.every(combination => arraySum(combination) === sum),
'Sum of every combination should be correct',
);
const res4 = sumOfCombinations([54, 234, 12, 99, 10], sum);
assert.equal(res4.length, 1, "should've found 1 combination");
assert.ok(
res4.every(combination => arraySum(combination) === sum),
'Sum of every combination should be correct',
);
console.log('all tests passed');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment