Skip to content

Instantly share code, notes, and snippets.

@ogallagher
Created June 10, 2021 18:33
Show Gist options
  • Save ogallagher/5c013e500f9e7cefddc0c593c52cfa52 to your computer and use it in GitHub Desktop.
Save ogallagher/5c013e500f9e7cefddc0c593c52cfa52 to your computer and use it in GitHub Desktop.
Generate combinations using elements from an array
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