【发布时间】:2014-07-16 01:11:34
【问题描述】:
如何找到替换字符串的所有可能组合或排列?与此答案类似,但此答案仅显示在被替换位置具有相同字符的不同组合:https://stackoverflow.com/a/22131499/1360374。
subs = {"a" => ["a", "@"], "i" => ["i", "!"], "s" => ["s", "$", "&"]}
string = "this is a test"
a = subs.values
a = a.first.product(*a.drop(1))
a.each do |a|
p [subs.keys, a].transpose.each_with_object(string.dup){|pair, s| s.gsub!(*pair)}
end
提供:
"this is a test"
"thi$ i$ a te$t"
"thi& i& a te&t"
"th!s !s a test"
"th!$ !$ a te$t"
"th!& !& a te&t"
"this is @ test"
"thi$ i$ @ te$t"
"thi& i& @ te&t"
"th!s !s @ test"
"th!$ !$ @ te$t"
"th!& !& @ te&t"
我正在尝试获得所有不同的排列:
"this is a test"
"this i$ a te$t"
"thi& is a te&t"
"th!s !s a test"
etc...
【问题讨论】:
标签: ruby-on-rails ruby algorithm combinations permutation