【问题标题】:All possible permutations or combinations of a selected character substitution's in a string in ruby w/ permutationsruby 字符串中所有可能的排列或所选字符替换的组合,带排列
【发布时间】: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


    【解决方案1】:

    这是你想要的吗?

    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
    }
    

    【讨论】:

    • 不幸的是,这给出了与其他答案相同的结果;我正在寻找替换字符的所有排列。不过还是谢谢。
    • 抱歉,我没有仔细阅读您的问题。这是你想要的吗? (也许你花了太多篇幅来描述你不想要的解决方案哈哈。)
    • 太棒了!谢谢!我相信您的回答会对其他人有所帮助,我注意到这是论坛中的热门话题,很多人都无法弄清楚...
    • Array#product 是这里的关键方法,而通常应该避免使用 imo 的 Array#flatten 可能在这里有它的用例。
    【解决方案2】:

    这个答案类似于鲍里斯的答案,但使用给定的输入(stringsubs),而不是创建一个新的东西,即 replacements

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

    【讨论】:

    • 谢谢。您如何在 subs 中包含多个字符,例如这是两个带有“oo”的字符,例如subs = {"oo" => ["oo", "00"], "a" => ["a", "@"], "i" => ["i", "!"], "s " => ["s", "$", "&"]}
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 2015-06-18
    • 2022-09-27
    • 1970-01-01
    • 2014-04-28
    相关资源
    最近更新 更多