2014-07-16 39 views
0

我將如何查找替代字符串的所有可能的組合或排列?與此答案類似,但此答案僅顯示替換位置中具有相同字符的不同組合:https://stackoverflow.com/a/22131499/1360374所有可能的排列組合或選定的字符替換字符串中的紅寶石w /排列

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" 
"this i$ a te$t" 
"thi& is a te&t" 
"th!s !s a test" 

etc... 

回答

0

這是你想要的嗎?

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

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 
} 
+0

不幸的是,這給出了與其他答案相同的結果;我正在尋找替換字符的所有排列。不過謝謝。 – Fretta

+0

對不起,我沒有仔細閱讀你的問題。這是你想要的嗎? (也許你用太多的空間來描述你不想要的東西了。) –

+0

太棒了!謝謝!我相信你的答案會幫助許多其他人,我注意到這是很多人無法弄清楚的論壇上的熱門話題...... – Fretta

0

這個答案是類似於鮑里斯的,但使用給定的輸入(stringsubs),而不是創建一個新的東西,即replacements

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

謝謝。你將如何在子目錄中包含多個字符這裏有兩個帶「oo」的字符,例如subs = {「oo」=> [「oo」,「00」],「a」=> [「a」,「@」],「i」=> [「i」,「!」],「s 「=> [」s「,」$「,」&「]} – Fretta

相關問題