ruby w /排列中字符串中所选字符替换的所有可能排列或组合

时间:2014-07-16 01:11:35

标签: ruby-on-rails ruby algorithm combinations permutation

如何找到替换字符串的所有可能组合或排列?与此答案类似,但此答案仅显示被替换位置中具有相同字符的不同组合: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...

2 个答案:

答案 0 :(得分:0)

这是你想要的吗?

string = "this is a test"
p = ?a, ?i, ?s
q = ?@, ?!, [ ?$, ?& ]

replacements = Hash.new { |h, e| Array e }.tap do |h|
  p.zip( q ).each { |p, q| h[p] = p, *Array( q ) }
end
#=> {"a"=>["a", "@"], "i"=>["i", "!"], "s"=>["s", "$", "&"]}

puts string.split( '' ).map( &replacements.method( :[] ) ).reduce( &:product ).map { |e|
  e.flatten.join
}

答案 1 :(得分:0)

这个答案与Boris相似,但使用给定的输入(stringsubs),而不是必须创建一个新的东西,即replacements

string.split(//).map{ |l| subs[l] || [l] }.inject(&:product).map{ |a| a.flatten.join }