Created
June 10, 2021 18:33
-
-
Save ogallagher/5c013e500f9e7cefddc0c593c52cfa52 to your computer and use it in GitHub Desktop.
Generate combinations using elements from an array
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
function combinations(options,places) { | |
// options is array | |
// places is positive int | |
if (places <= 1) { | |
let c = [] | |
for (let o of options) { | |
c.push([o]) | |
} | |
return c | |
} | |
else { | |
let c = [] | |
for (let o of options) { | |
for (let subc of combinations(options,places-1)) { | |
c.push([o].concat(subc)) | |
} | |
} | |
return c | |
} | |
} | |
// example | |
combinations('abcde',2) // --> 'a','a' 'a','b' 'a','c' ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment