Last active
April 22, 2022 13:44
-
-
Save fronterior/847249048ffec762d672ef54f3a21293 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* combination(array, n) { | |
if (n === 1) { | |
for (const item of array) yield [item]; | |
return; | |
} | |
for (let i = 0; i < array.length - n + 1; i++) { | |
const stack = [[[array[i]], array.slice(i + 1)]]; | |
while (stack.length) { | |
const [comb, rest] = stack.shift(); | |
for (let i = 0; i < rest.length; i++) { | |
const newComb = [...comb, rest[i]]; | |
if (newComb.length === n) { | |
yield newComb; | |
continue; | |
} else { | |
const newRest = rest.slice(i + 1); | |
stack.push([newComb, newRest]); | |
} | |
} | |
} | |
} | |
} | |
function* combinationAll(array) { | |
const { length } = array; | |
for (let i = 1; i <= length; i++) | |
for (const result of combination(array, i)) yield result; | |
} | |
console.log('combination', ...combination([1, 2, 3, 4], 3)); | |
console.log('combinationAll', ...combinationAll([1, 2, 3, 4])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment