获取,而preserving顺序排列项的所有组合 - 红宝石 [英] Getting all combinations of array items while preserving sequence - Ruby

查看:111
本文介绍了获取,而preserving顺序排列项的所有组合 - 红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于字符串数组

["the" "cat" "sat" "on" "the" "mat"]

我希望得到的序列项目的所有组合,从任意起始位置,例如

I'm looking to get all combinations of items in sequence, from any starting position, e.g.

["the"]
["the" "cat"]
["the" "cat" "sat"]
...
["cat" "sat" "on" "the" "mat"]
["sat" "on" "the" "mat"]
["on" "the" "mat"]
...
["sat" "on"]
["sat" "on" "the"]

组合出原始序列或缺失的元素不允许的,例如

Combinations out of the original sequence or with missing elements are disallowed, e.g.

["sat" "mat"] # missing "on"
["the" "on"]  # reverse order

我也想知道如果此操作有一个特别的名字,或者如果有描述它的一个更合适的方法。

I'd also like to know if this operation has a particular name or if there's a neater way of describing it.

感谢。

推荐答案

只是遍历每个起始位置和在每个可能的结束位置的每个起始位置:

Just iterate over each starting position and for each starting position over each possible end position:

arr = ["the", "cat", "sat", "on", "the", "mat"]
(0 ... arr.length).map do |i|
  (i ... arr.length).map do |j|
    arr[i..j]
  end
end.flatten(1)
#=> [["the"], ["the", "cat"], ["the", "cat", "sat"], ["the", "cat", "sat", "on"], ["the", "cat", "sat", "on", "the"], ["the", "cat", "sat", "on", "the", "mat"], ["cat"], ["cat", "sat"], ["cat", "sat", "on"], ["cat", "sat", "on", "the"], ["cat", "sat", "on", "the", "mat"], ["sat"], ["sat", "on"], ["sat", "on", "the"], ["sat", "on", "the", "mat"], ["on"], ["on", "the"], ["on", "the", "mat"], ["the"], ["the", "mat"], ["mat"]]

需要为红宝石1.8.7+(或反向移植)压平(1)

这篇关于获取,而preserving顺序排列项的所有组合 - 红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆