In Ruby I have three nested loops:
array.each do |a|
array.each do |b|
array.each do |c|
puts a * b * c
end
end
end
How can I optimize this code, if the number of nested loops can be increased to 5-10 and more iterations?
Example:
array.each do |a|
array.each do |b|
array.each do |c|
array.each do |d|
array.each do |e|
array.each do |f|
puts a * b * c * d * e * f
end
end
end
end
end
end
You can do something like this:
array.repeated_combination(array.size).each do |combination|
puts combination.reduce(:*)
end
Array#repeated_combination
returns an enumerator that yields all possible combinations.
Because this method generates all combinations before printing any output is might take a while depending on the size of the array. Keep in mind that the number of possible combinations increases quite fast: O(nⁿ)
with n
being the number of elements in the array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With