Created
November 24, 2014 03:43
-
-
Save timuruski/15eccf215418a735b090 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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