Skip to content

Instantly share code, notes, and snippets.

@fronterior
Last active April 22, 2022 13:43
Show Gist options
  • Save fronterior/df0cff0d60ffa0b6a788b530d38cb5da to your computer and use it in GitHub Desktop.
Save fronterior/df0cff0d60ffa0b6a788b530d38cb5da to your computer and use it in GitHub Desktop.
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