Skip to content

Instantly share code, notes, and snippets.

@cetteup
Last active May 7, 2024 16:10
Show Gist options
  • Save cetteup/69a2876d5f9e48bde3aac0227f6619fe to your computer and use it in GitHub Desktop.
Save cetteup/69a2876d5f9e48bde3aac0227f6619fe to your computer and use it in GitHub Desktop.
Mutating combination function (zero changes to array length)
function combine(strings: string[], length: number): string[] {
// Init results array of required length, filled with empty strings
const combinations = Array(strings.length**length).fill('')
for (let i = length; i > 0; i--) {
for (let j = 0; j < combinations.length; j++) {
combinations[j] += strings[Math.floor(j/(strings.length**(i-1)))%strings.length]
}
}
return combinations
}
const combined = combine(["a", "b", "c"], 3)
console.log(combined)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment