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 or 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
+4
source share
2 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 gives all possible combinations.

Since this method generates all the combinations before printing, any output may take some time depending on the size of the array. Keep in mind that the number of possible combinations increases quite quickly: O(nⁿ)with nis the number of elements in the array.

+8
source

( @spickermann)

# 1

array = [1,2,3]
n = 4
arr = array.product(*[array]*(n-1)).map { |arr| arr.reduce(:*) }
arr.size #=> 81 = arr.size**n
arr.each { |e| puts e }
1
2
3
2
4
6
3
6
9
...
54
27
54
81

, map each arr.reduce(:*) puts arr.reduce(:*).

# 2

sz = array.size
(0...sz**n).map { |i| i.to_s(sz)
                       .rjust(n,'_')
                       .chars
                       .reduce(1) { |t,e| t * (e=='_' ? 1 : array[e.to_i]) }
                }
0

All Articles