Ka Mok
Ka Mok

Reputation: 1988

How to get the permutation of an array without changing the order of its values?

For this array: a = [8, 2, 22, 97, 38, 15], how can I get all sub-arrays of length three, in the fashion of a sliding window, without disturbing the order of the values.?

For example, the result should be: [[8,2,22],[2,22,97],[22,97,38],[97,38,15]]

Upvotes: 0

Views: 250

Answers (2)

Vaibhav Dhoke
Vaibhav Dhoke

Reputation: 459

You could pass a parameter for like this to achieve

a.each_con(3)

This returns an Enumeration which you may iterate over. To turn the Enumeration into an array, call the to_a method:

a.each_cons(3).to_a

Upvotes: 2

Ka Mok
Ka Mok

Reputation: 1988

Here is what I came up with:

def ordered_permutations(array: [1,2,3], length: n)
  array = array.dup
  [].tap do |result|
    (array.count - (length - 1)).times do
      result << array[0..(length-1)]
      array.shift
    end
  end
end

p ordered_permutations(array: a, length: 3)

Upvotes: 0

Related Questions