0

如果我有一个诸如“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']
4

4 回答 4

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
于 2012-10-17T19:12:34.780 回答
1

正则表达式对这类问题没有帮助。我建议在 Ruby 1.9中使用方便的Array#combination(n)函数:

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"]]
于 2012-10-17T19:19:16.950 回答
0

不,正则表达式不适合这里。当然,您可以像这样匹配一个或两个字符:

strn.scan(/[a-z][a-z]?/)
# matches: ['ab', 'cd', 'e']

但是您不能使用正则表达式生成所有组合的(2d)列表。

于 2012-10-17T19:08:19.753 回答
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"]]
于 2012-10-17T20:16:45.897 回答