Skip to content

Instantly share code, notes, and snippets.

@BideoWego
Last active November 26, 2015 18:32
Show Gist options
  • Save BideoWego/6d0cf548719d7496130a to your computer and use it in GitHub Desktop.
Save BideoWego/6d0cf548719d7496130a to your computer and use it in GitHub Desktop.
Create all the combinations of 0 to n with e positions
# Array.new(2**5) do |i|
# [i / 2**4, i / 2**3 % 2, i / 2**2 % 2, i / 2 % 2, i % 2]
# end
# integer_combinations(2, 5)
# => [[0, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 1, 0], [0, 0, 0, 1, 1], [0, 0, 1, 0, 0], [0, 0, 1, 0, 1], [0, 0, 1, 1, 0], [0, 0, 1, 1, 1], [0, 1, 0, 0, 0], [0, 1, 0, 0, 1], [0, 1, 0, 1, 0], [0, 1, 0, 1, 1], [0, 1, 1, 0, 0], [0, 1, 1, 0, 1], [0, 1, 1, 1, 0], [0, 1, 1, 1, 1], [1, 0, 0, 0, 0], [1, 0, 0, 0, 1], [1, 0, 0, 1, 0], [1, 0, 0, 1, 1], [1, 0, 1, 0, 0], [1, 0, 1, 0, 1], [1, 0, 1, 1, 0], [1, 0, 1, 1, 1], [1, 1, 0, 0, 0], [1, 1, 0, 0, 1], [1, 1, 0, 1, 0], [1, 1, 0, 1, 1], [1, 1, 1, 0, 0], [1, 1, 1, 0, 1], [1, 1, 1, 1, 0], [1, 1, 1, 1, 1]]
def integer_combinations_of(n, e)
Array.new(n**e) do |i|
a = []
if e > 0
a << i / n**(e - 1) if e > 1
if e > 2
j = e - 2
while j > 0
a << i / n**j % n
j -= 1
end
end
end
if n > 0
a << i % n
else
a << i
end
a
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment