Skip to content

Instantly share code, notes, and snippets.

@BideoWego
Created August 29, 2015 07:57
Show Gist options
  • Save BideoWego/a91412fb4342cef63271 to your computer and use it in GitHub Desktop.
Save BideoWego/a91412fb4342cef63271 to your computer and use it in GitHub Desktop.
Generates an exhaustive set of number combinations consisting of `e` positions in each combination and each number in the combination is a value 0 to `n`
# Generates an exhaustive set of number combinations
# consisting of `e` positions in each combination
# and each number in the combination is a value 0 to `n`
#
# - examples:
# set(2, 2)
# => [[0, 0], [0, 1], [1, 0], [1, 1]]
#
# set(3, 3)
# => [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 2, 0], [0, 2, 1], [0, 2, 2], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2], [1, 2, 0], [1, 2, 1], [1, 2, 2], [2, 0, 0], [2, 0, 1], [2, 0, 2], [2, 1, 0], [2, 1, 1], [2, 1, 2], [2, 2, 0], [2, 2, 1], [2, 2, 2]]
def set(n, e)
Array.new(n**e) do |i|
a = []
if e > 0
j = e - 1
while j >= 0
a << i / n**j % n
j -= 1
end
end
a
end
end
if __FILE__ == $0
n = 6
e = 4
a = base(n, e)
a.each {|i| puts i.join(' ')}
puts "Combinations (#{n}, #{e}): #{a.length}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment