How to combination/permutation in ruby?

后端 未结 3 1067
清歌不尽
清歌不尽 2021-01-18 19:46

I\'ve this familiar question that looks like permutation/combination of the Math world.

How can I achieve the following via ruby?

badges = \"1-2-3\"
         


        
3条回答
  •  被撕碎了的回忆
    2021-01-18 20:01

    Functional approach:

    bs = "1-2-3".split("-")
    strings = 1.upto(bs.size).flat_map do |n| 
      bs.permutation(n).map { |vs| vs.join("-") } 
    end
    #=> ["1", "2", "3", "1-2", "1-3", "2-1", "2-3", "3-1", "3-2", "1-2-3", "1-3-2", "2-1-3", "2-3-1", "3-1-2", "3-2-1"]
    

提交回复
热议问题