【问题标题】:Getting all combinations of array items while preserving sequence - Ruby在保留序列的同时获取数组项的所有组合 - Ruby
【发布时间】:2010-08-11 10:25:59
【问题描述】:

给定一个字符串数组

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

我希望从任何起始位置按顺序获取所有项目组合,例如

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

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

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

我还想知道这个操作是否有特定的名称,或者是否有更简洁的描述方式。

谢谢。

【问题讨论】:

    标签: ruby arrays sequence combinations


    【解决方案1】:

    如果你喜欢单线,你可以试试

    (0..arr.length).to_a.combination(2).map{|i,j| arr[i...j]}
    

    顺便说一句,我认为这些被称为数组的“所有子序列”。

    【讨论】:

    • 他问的是子串,而不是子序列。每个子串也是一个子序列,但并非所有子序列都是子串。例如,235123456 的子序列,但不是子字符串。
    • 谢谢,我不知道有什么区别。因此,子字符串需要是原始数组中的连续元素,而子序列则不需要。
    • 在任何情况下,上面都是找到子字符串,而不是子序列,所以,只是语义......优雅的解决方案:)
    【解决方案2】:

    只需遍历每个起始位置以及每个可能的结束位置的起始位置:

    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"]]
    

    flatten(1) 需要 ruby​​ 1.8.7+(或 backports)。

    【讨论】:

    • 我冒昧地编辑了范围以使用... 而不是-1。另请注意,Ruby 1.9.2 引入了flat_map,它基本上等同于map{}.flatten(1)。也可通过backports 获得:-)
    【解决方案3】:

    在这里你可以得到所有的组合

    (1...arr.length).map{ | i | arr.combination( i ).to_a }.flatten(1)
    

    【讨论】:

      猜你喜欢
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 2018-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多