如何在不改变其值顺序的情况下获得数组的排列?

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

对于这个数组:a = [8, 2, 22, 97, 38, 15],如何在不打乱值顺序的情况下,以滑动 window 的方式获取长度为 3 的所有子数组。?

例如,结果应该是:[[8,2,22],[2,22,97],[22,97,38],[97,38,15]]

这是我想出的:

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)

你可以像这样传递一个参数来实现

a.each_con(3)

此 returns 一个您可以迭代的枚举。要将 Enumeration 转换为数组,请调用 to_a 方法:

a.each_cons(3).to_a