How to split a string into consecutive substrings of length at most 3 in all possible ways?

后端 未结 4 821
清歌不尽
清歌不尽 2021-01-03 01:11

I am trying to take a string, between length 1 and 10, and output all possible ways of breaking up the string into consecutive substrings that are of sizes 1, 2, or 3. For e

4条回答
  •  执念已碎
    2021-01-03 02:15

    Here's another:

    class String
      def splitup(prefix=nil)
        parts = []
        if size <= 3
          parts << [prefix,self].compact * ","
        end
        (1..([size,3].min)).each do |p|
          next if p >= size
          parts << slice(p..-1).splitup([prefix,slice(0,p)].compact * ",")
        end
        parts
      end
    
      def report
        flat = splitup.flatten.sort_by {|x| [-x.size,x]}
        puts
        puts "#{flat.size} permutations of #{self}"
        puts flat
      end
    end
    

    and then

    >> "123456".report
    
    24 permutations of 123456
    1,2,3,4,5,6
    1,2,3,4,56
    1,2,3,45,6
    1,2,34,5,6
    1,23,4,5,6
    12,3,4,5,6
    1,2,3,456
    1,2,34,56
    1,2,345,6
    1,23,4,56
    1,23,45,6
    1,234,5,6
    12,3,4,56
    12,3,45,6
    12,34,5,6
    123,4,5,6
    1,23,456
    1,234,56
    12,3,456
    12,34,56
    12,345,6
    123,4,56
    123,45,6
    123,456
    

提交回复
热议问题