Created
May 27, 2022 21:46
-
-
Save aryelgois/cf21e2d022812df547047a0820ca22b2 to your computer and use it in GitHub Desktop.
Get combinations of array elements
This file contains 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
export function* getCombinations<T>(arr: T[], size: number): Generator<T[]> { | |
if (size < 1) { | |
throw new Error('Combination size must be at least 1') | |
} | |
if (arr.length === 0) { | |
yield [] | |
} else if (size === 1) { | |
for (const el of arr) { | |
yield [el] | |
} | |
} else { | |
const limit = arr.length - size + 1 | |
for (let i = 0; i < limit; i++) { | |
for (const result of getCombinations(arr.slice(i + 1), size - 1)) { | |
yield [arr[i], ...result] | |
} | |
} | |
} | |
} | |
export function* getVariableCombinations<T>(arr: T[], min: number, max: number) { | |
for (let size = min; size <= max; size++) { | |
yield* getCombinations(arr, size) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment