【问题标题】:Combine multiple strings in array 1 to form array 2将数组 1 中的多个字符串组合成数组 2
【发布时间】:2013-10-03 21:18:18
【问题描述】:

我有一个字符串数组“A”和一个目标字符串“B”。 B弦 仅包含从 a 到 z 的字符,不包含空格。我需要一个红宝石函数 它返回字符串数组,该数组表示从数组 A 的元素形成 B 的所有可能方式。返回组合的顺序无关紧要。 A中的单词可以多次使用。

例子:

A = [‘x’, ‘y’, ‘z’, 'yz',‘xy’, ‘xyz’] 

B = ‘xyz’ 

method(A, B) => [x y z, x yz, xyz, xy z]  

我研究了置换方法,但无法让它发挥作用。

【问题讨论】:

  • 您能否提供一个迄今为止尝试过的示例,如果可能的话,请提供输出应该是什么样子的示例?
  • A = ['x', 'y', 'z', 'yy', 'yz'] B = 'xyyz' method_name(A, B) => ['x y yz', 'xy yz' 等] 我试过扫描和映射 - 太令人沮丧了!我是 Ruby 新手,我总是很难过。

标签: ruby


【解决方案1】:

这是一个不遍历排列的递归解决方案:

def find_possible_combinations( list, str )
  list.select { |a| str.start_with? a }.map do |a|
    if a == str
      [a]
    else
      find_possible_combinations( list-[a], str.slice(a.length..-1) )
        .map { |c| "#{a} #{c}" }
    end
  end.flatten
end

puts "#{find_possible_combinations( %w( x y z yz xy xyz ), 'xyz' )}"

输出:

["x y z", "x yz", "xy z", "xyz"]

【讨论】:

    【解决方案2】:
    A = %w[x y z yz xy xyz] 
    B = "xyz"
    SIZE = B.size
    
    def combos
      (1..SIZE).inject([]) {|c, n| c.concat(combos_by_size(n))}.reject(&:empty?)
    end
    
    # Select all combinations of size n having SIZE characters
    def combos_by_size(n)
      A.combination(n).to_a.inject([]) {|c, a| c.concat(matching_combos(a)) if a.join.size == SIZE; c}.reject(&:empty?)
    end
    
    
    # Select all matching combinations using all elements of array a
    def matching_combos(a)
      a.permutation.to_a.select {|p| p.join == B}
    end
    
    combos # => [["xyz"], ["x", "yz"], ["xy", "z"], ["x", "y", "z"]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      相关资源
      最近更新 更多