Skip to content

Instantly share code, notes, and snippets.

@timuruski
Created November 24, 2014 03:43
Show Gist options
  • Save timuruski/15eccf215418a735b090 to your computer and use it in GitHub Desktop.
Save timuruski/15eccf215418a735b090 to your computer and use it in GitHub Desktop.
# Generates combinations of letters or numbers, or anything really. The combinations
# include repeating values, unlike Ruby's regular Array#permutation method.
#
# Usage:
# generate('a'..'c', 3) do |seq|
# puts seq.inspect #=> [a,a,a], [a,a,b], [a,a,c], [a,b,a]...
# end
def generate(range, comb_len)
range = range.to_a
range_len = range.length
(range_len ** comb_len).times do |q|
# Converts a number into digits of an arbitrary base,
# eg. 13 in base 3 -> [1,1,1]
indices = Array.new(comb_len) { q, r = q.divmod(range_len); r }.reverse
# Uses base conversion indices to produce combinations.
yield range.values_at(*indices)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment