如果我有一个字符串,例如'abcde',我想获得一个包含1或2个字母的所有组合的二维数组。
[ ['a', 'b', 'c', 'd', 'e'], ['ab', 'c', 'de'], ['a', 'bc', 'd', 'e'] ...
我将如何做到这一点?
我想在ruby中这样做,并认为我应该使用正则表达式。我尝试过使用
strn = 'abcde'
strn.scan(/[a-z][a-z]/)
但这只会给我两组不同的字符
['ab', 'cd']
答案 0 :(得分:1)
我认为应该这样做(尚未经过测试):
def find_letter_combinations(str)
return [[]] if str.empty?
combinations = []
find_letter_combinations(str[1..-1]).each do |c|
combinations << c.unshift(str[0])
end
return combinations if str.length == 1
find_letter_combinations(str[2..-1]).each do |c|
combinations << c.unshift(str[0..1])
end
combinations
end
答案 1 :(得分:1)
正则表达式对这类问题没有帮助。我建议在Ruby 1.9中使用方便的Array#combination(n)
function:
def each_letter_and_pair(s)
letters = s.split('')
letters.combination(1).to_a + letters.combination(2).to_a
end
ss = each_letter_and_pair('abcde')
ss # => [["a"], ["b"], ["c"], ["d"], ["e"], ["a", "b"], ["a", "c"], ["a", "d"], ["a", "e"], ["b", "c"], ["b", "d"], ["b", "e"], ["c", "d"], ["c", "e"], ["d", "e"]]
答案 2 :(得分:0)
不,正则表达式不适合这里。当然你可以匹配这样的一个或两个字符:
strn.scan(/[a-z][a-z]?/)
# matches: ['ab', 'cd', 'e']
但您无法使用正则表达式生成所有组合的(2d)列表。
答案 3 :(得分:0)
功能递归方法:
def get_combinations(xs, lengths)
return [[]] if xs.empty?
lengths.take(xs.size).flat_map do |n|
get_combinations(xs.drop(n), lengths).map { |ys| [xs.take(n).join] + ys }
end
end
get_combinations("abcde".chars.to_a, [1, 2])
#=> [["a", "b", "c", "d", "e"], ["a", "b", "c", "de"],
# ["a", "b", "cd", "e"], ["a", "bc", "d", "e"],
# ["a", "bc", "de"], ["ab", "c", "d", "e"],
# ["ab", "c", "de"], ["ab", "cd", "e"]]