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

后端 未结 4 831
清歌不尽
清歌不尽 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:13

    It took me quite a while to figure this out, its a much harder problem then I first though. But eventually I hit upon this solution:

    def combinations(s)
      c = (s.length > 3) ? [] : [[s]]
      max = [4, s.length].min
      (1...max).inject(c) do |c, i|
        combinations(s[i..-1]).inject(c) do |c, tail|
          c.push([s[0...i]] + tail)
        end
      end
    end
    
    combinations("12345").each { |c| p c }
    

    Produces:

    ["1", "2", "345"]
    ["1", "2", "3", "45"]
    ["1", "2", "3", "4", "5"]
    ["1", "2", "34", "5"]
    ["1", "23", "45"]
    ["1", "23", "4", "5"]
    ["1", "234", "5"]
    ["12", "345"]
    ["12", "3", "45"]
    ["12", "3", "4", "5"]
    ["12", "34", "5"]
    ["123", "45"]
    ["123", "4", "5"]
    

提交回复
热议问题