Skip to content

Instantly share code, notes, and snippets.

@jakobmattsson
Last active December 31, 2015 20:09
Show Gist options
  • Save jakobmattsson/8038195 to your computer and use it in GitHub Desktop.
Save jakobmattsson/8038195 to your computer and use it in GitHub Desktop.
Combinations - kodapor
flatten = (arrays) ->
result = []
arrays.forEach (array) ->
result = result.concat(array)
result
combinations = (n, values) ->
return [[]] if n <= 0
flatten [0 ... values.length].map (x) ->
head = values[x]
rest = values.slice(x+1)
subCombinations = combinations(n-1, rest)
subCombinations.map (subCombination) -> [head].concat(subCombination)
allCombinations = (n, values) ->
flatten [1 .. n].map (newN) ->
combinations(newN, values)
console.log allCombinations(4, [5, 4, 3, 2, 1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment