Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimize nested loops in Ruby

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
like image 605
Sergey Blohin Avatar asked Feb 12 '23 16:02

Sergey Blohin


1 Answers

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.

like image 102
spickermann Avatar answered Feb 20 '23 12:02

spickermann