Is there a easier, cleaner way to write code like this:
(1..10).each do |i|
(1..10).each do |j|
(1..10).each do |k|
(1..10).each do |l|
puts "#{i} #{j} #{k} #{l}"
end
end
end
end
Ideally I'd be able to do something like...
(1..10).magic(4) { |i, j, k, l| puts "#{i} #{j} #{k} #{l}" }
Or even better...
magic(10, 4) { |i, j, k, l| puts "#{i} #{j} #{k} #{l}" }
If there's not something built in, how would I write a method like the last one?
I've taken the liberty of changing the order of your
magic
parameters under the assumption that base 10 is more common and optional:Explanation:
By translating the original problem from
1..10
to0..9
and concatenating the digits we see that the output is just counting, with access to each digit.So that's what my code above does. It counts from 0 up to the maximum number (based on the number of digits and allowed values per digit), and for each number it:
Converts the number into the appropriate 'base':
i.to_s(base) # e.g. 9.to_s(8) => "11", 11.to_s(16) => "b"
Uses
String#%
to pad the string to the correct number of characters:"%#{digits}s" % ... # e.g. "%4s" % "5" => " 5"
Turns this single string into an array of single-character strings:
str.scan(/./) # e.g. " 31".scan(/./) => [" ","3","1"]
Note that in Ruby 1.9 this is better done with
str.chars
Converts each of these single-character strings back into a number:
n.to_i(base) # e.g. "b".to_i(16) => 11, " ".to_i(3) => 0
Adds 1 to each of these numbers, since the desire was to start at 1 instead of 0
Splats this new array of numbers as arguments to the block, one number per block param:
yield *parts
If you're on Ruby 1.9, you can do this:
In Ruby 1.8:
dmarkow's solution (I believe) materializes the ranges which, at least in theory, uses more memory than you need. Here's a way to do it without materializing the ranges:
That said, performance is a tricky thing and I don't know how efficient Ruby is with function calls, so maybe sticking to library functions is the fastest way to go.
Update: Took Phrogz' suggestion and put
magic_
insidemagic
. (Update: Took Phrogz' suggestion again and hopefully did it right this time withlambda
instead ofdef
).Update:
Array#product
returns anArray
, so I'm assuming that is fully materialized. I don't have Ruby 1.9.2, but Mladen Jablanović pointed out thatArray#repeated_permutation
probably doesn't materialize the whole thing (even though the initial range is materialized withto_a
).