Skip to content

Instantly share code, notes, and snippets.

@ElManouche
Last active March 2, 2017 15:05
Show Gist options
  • Save ElManouche/fe2b46c805da6dee1bb8efaaa9dc4abb to your computer and use it in GitHub Desktop.
Save ElManouche/fe2b46c805da6dee1bb8efaaa9dc4abb to your computer and use it in GitHub Desktop.
Combinations - https://repl.it/GE1s/0
def combinations(lengths)
return nil if lengths.nil?
(0..lengths.reduce(:*) - 1).map do |line|
(0..lengths.count - 1).map do |row|
sub_pos = lengths.slice(row + 1, lengths.count).reduce(:*) || 1
line / sub_pos % lengths[row]
end
end
end
combinations [2,2,2]
# returns [[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment