Created
October 12, 2023 05:51
-
-
Save Chesare22/54476ac4f5711a26c360260ba262f167 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getCombinations = (availableNumbers = [], length = 0) => { | |
if(length === 0) { | |
return [] | |
} | |
if(availableNumbers.length < length) { | |
return [] | |
} | |
if(length === 1) { | |
return availableNumbers.map(number => [number]) | |
} | |
// get all the combinations that use the first number | |
const [first, ...rest] = availableNumbers | |
const combinationsUsingTheFirstNumber = getCombinations(rest, length -1) | |
.map((val) => [first, ...val]) | |
const combinationsWithoutFirst = getCombinations(rest, length) | |
return [...combinationsUsingTheFirstNumber, ...combinationsWithoutFirst] | |
} | |
const sumArray = array => array.reduce((a, b) => a + b, 0) | |
const _groupBySum = (accBySum, array) => { | |
const sum = sumArray(array) | |
const accumulatedWithMatchingSum = accBySum[sum] | |
if(accumulatedWithMatchingSum) { | |
return { | |
...accBySum, | |
[sum]: [...accumulatedWithMatchingSum, array] | |
} | |
} | |
return { | |
...accBySum, | |
[sum]: [array] | |
} | |
} | |
const groupBySum = (array = []) => array.reduce(_groupBySum, {}) | |
const filterRecord = (condition) => (record) => { | |
return Object.fromEntries(Object.entries(record).filter(([key, value]) => condition(value, key))) | |
} | |
// console.log( | |
// filterRecord( | |
// (array) => array.length >= 8 | |
// )( | |
// groupBySum( | |
// getCombinations( | |
// [1, 2, 3, 4, 5, 6, 7, 8, 9], | |
// 4 | |
// ) | |
// ) | |
// ) | |
// ) | |
console.log(getCombinations([2,3,4,5], 3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment