我有一个字符串数组“A”和一个目标字符串“B”。B 字符串仅包含从 a 到 z 的字符,并且不包含空格。我需要一个 ruby 函数,它返回字符串数组,该数组表示从数组 A 的元素形成 B 的所有可能方式。返回组合的顺序无关紧要。A中的单词可以多次使用。
例子:
A = [‘x’, ‘y’, ‘z’, 'yz',‘xy’, ‘xyz’]
B = ‘xyz’
method(A, B) => [x y z, x yz, xyz, xy z]
我研究了排列方法,但无法让它工作。
我有一个字符串数组“A”和一个目标字符串“B”。B 字符串仅包含从 a 到 z 的字符,并且不包含空格。我需要一个 ruby 函数,它返回字符串数组,该数组表示从数组 A 的元素形成 B 的所有可能方式。返回组合的顺序无关紧要。A中的单词可以多次使用。
例子:
A = [‘x’, ‘y’, ‘z’, 'yz',‘xy’, ‘xyz’]
B = ‘xyz’
method(A, B) => [x y z, x yz, xyz, xy z]
我研究了排列方法,但无法让它工作。
这是一个不遍历排列的递归解决方案:
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"]
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"]]