Naveen Agarwal
Naveen Agarwal

Reputation: 579

How to convert static Ruby code into dynamic Ruby code

The following code creates an array of arrays. Each array is of size 5, with possible values ranging from 0 to 7.

arr = []
8.times do |n1|
  8.times do |n2|
    8.times do |n3|
      8.times do |n4|
        8.times do |n5|
          arr << [n1, n2, n3, n4, n5]
        end
      end
    end
  end
end
arr.size # => 32768

If 8 (in 8.times) and 5 (5 times nested) are dynamic, then how can this code be converted into dynamic code without its function changed? For example, if I have to get an array of size 6 each instead of 5 (as in the current example), then how should this code be re-written?

Upvotes: 0

Views: 105

Answers (1)

Ilya
Ilya

Reputation: 13487

It seems like you are looking for Array#repeated_permutation:

(0..7).to_a.repeated_permutation(5)

Lets check:

(0..7).to_a.repeated_permutation(5).size
#=> 32768
(0..7).to_a.repeated_permutation(5).first(10)
#=> [[0, 0, 0, 0, 0], 
#    [0, 0, 0, 0, 1], 
#    [0, 0, 0, 0, 2], 
#    [0, 0, 0, 0, 3], 
#    [0, 0, 0, 0, 4], 
#    [0, 0, 0, 0, 5], 
#    [0, 0, 0, 0, 6], 
#    [0, 0, 0, 0, 7], 
#    [0, 0, 0, 1, 0], 
#    [0, 0, 0, 1, 1]]

Note: repeated_permutation returns Enumerator.

Upvotes: 7

Related Questions