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
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"]