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

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

    Here's a working function. May be not optimal as I didn't spend much time on it.

    str = "1234567890"
    
    def f(s, n)
        return [[]] if s.empty?
    
        (1..[n, s.length].min).map{|c| f(s[c..-1], n).map{|a| [s[0, c]] + a}}.inject(&:+)
    end
    
    puts f(str, 3).collect{|l| l * "\t"}
    

    EDIT: Made it a bit shorter and the length is now passed as second parameter to function for flexibility.

提交回复
热议问题