Last active
May 7, 2024 16:10
-
-
Save cetteup/69a2876d5f9e48bde3aac0227f6619fe to your computer and use it in GitHub Desktop.
Mutating combination function (zero changes to array length)
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 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