Last active
April 22, 2022 13:43
-
-
Save fronterior/df0cff0d60ffa0b6a788b530d38cb5da 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
function* numberOfCases(array, count) { | |
const stack = [[[], array]]; | |
let target; | |
while (target = stack.shift()) { | |
const [c, rest] = target; | |
if (c.length === count) yield c; | |
else stack.push(...rest.map((item, i) => [[...c, item], rest.filter((_, j) => j !== i)])); | |
} | |
} | |
function* numberOfCasesAll(array) { | |
const { length } = array; | |
for (let i = 1; i <= length; i++) | |
for (const result of numberOfCases(array, i)) yield result; | |
} | |
console.log('numberOfCasesByCount', ...numberOfCases([2,4,6,8,10], 3)); | |
console.log('numberOfCases', ...numberOfCasesAll([1,2,3])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment