我想查找保存顺序的字符串的所有组合。有没有在Ruby中内置的方法来实现这一目标?保存顺序的Ruby字符串/数组组合保留顺序
例如,"abcd".all_combinations
应该给输出:
a
b
c
d
ab
bc
cd
abc
bcd
abcd
我想查找保存顺序的字符串的所有组合。有没有在Ruby中内置的方法来实现这一目标?保存顺序的Ruby字符串/数组组合保留顺序
例如,"abcd".all_combinations
应该给输出:
a
b
c
d
ab
bc
cd
abc
bcd
abcd
可能不是理想的实现,但这个工程:
def combinations(str)
items = str.chars
(1..items.length).map { |i| items.each_cons(i).map(&:join) }.flatten
end
还要检查Enumerable#each_cons
。你也可以将它添加到String类是这样的:
class String
def combinations
items = self.chars
(1..items.length).map { |i| items.each_cons(i).map(&:join) }.flatten
end
end
'abcd'.combinations
正在发生的事情:
String#chars
。i
到字符串的长度:
Enumerable#each_cons
基本上返回长度i
的可能组合作为字符数组太。因此,如果i
是2,则items.each_cons(2)
结果将是[ ['a', 'b'], ['b', 'c'], ['c', 'd'] ]
.map(&:join)
部分基本上是调用每个阵列的该阵列的元件的Array#join
,所以它成为['ab', 'bc', 'cd']
(1..items.length).map { |i| items.each_cons(i).map(&:join) }
结果:[ ['a', 'b', 'c', 'd'], ['ab', 'bc', 'cd'], ['abc', 'bcd'], ['abcd'] ]
这是一个数组数组。我们把它叫做Array#flatten
,使它成为一个简单的数组(更多地阅读flatten链接)。这工作,非常感谢!我是Ruby的新手......你能向我们解释一下实施吗? – maddy
@maddy更新,希望有所帮助。您需要阅读链接方法的描述以更好地了解发生的事情。 –
@TamerShlash:您可以使用'Array#combination'代替'Enumberable#each_cons'也可以使用 –
没有内建函数完全符合您的要求。
String#each_cons看起来很有趣,因为Tamer指出。
下面是一个替代的解决方案:
def all_combos(str)
1.upto(str.length) do |segment_length|
0.upto(str.length - segment_length) do |starting_point|
puts str[starting_point, segment_length]
end
end
end
all_combos("abcd")
非常干净的解决方案。虽然我会让每个子字符串“产生”而不是打印它,所以你可以通过'all_combos('abcd'){| s |放入s}'。 – Stefan
起始和子串的结尾索引形成具有重复一个组合,为此,红宝石确实有一个内置的方法的图案。
class String
def all_combinations
idx = (0 ... self.size).to_a
idx.repeated_combination(2){|i,j| yield self[i..j]}
end
end
"abcd".all_combinations{|combo| puts combo}
'each_combination'可能是一个更好的名字。 – Stefan
它是否必须是内置方法? –
任何类型的实现都可以工作。但希望有一些类似object.combination的方法 – maddy
看看http://apidock.com/ruby/Array/combination –