## possible ways of splitting a string into n substrings

Question

I'm trying to write a method that would take 'abcd' as an input, and return:

```
["a b c d", "a b cd", "a bc d", "a bcd", "ab c d", "ab cd", "abc d", "abcd"]
```

so, all possible ways of splitting a string into n substrings that when you concatenage s1 + s2 + s3 + ... you get back the original string.

I have solved it like this, but I feel like there should be a faster and more straightforward way to do it.

```
def sequence(n)
[true, false].repeated_permutation(n).to_a
end
def breakdown4(string)
guide = sequence(string.length-1)
arr = []
guide.each do |i|
s = string.dup
counter = 0
i.each do |j|
if j
s.insert(counter+1, " ")
p counter
counter += 2
else
counter += 1
end
end
arr.push(s)
end
arr
end
```

any suggestions?

Show source

## Answers to possible ways of splitting a string into n substrings ( 4 )

A oneliner also using

`repeated_permutation`

(which I just learned from you :-):`repeated_permutation`

produces joints, like`[" ", "", " "]`

.`zip`

pairs them to the letters, like`[["a", " "], ["b", ""], ["c", " "], ["d", nil]]`

.`join`

turns all parts into strings and joins them, like`"a bc d"`

.(Note that

`nil`

becomes the empty string and that`join`

works recursively, effectively flattening the whole structure).Previous solutions I came up with before I knew

`repeated_permutation`

:The basic idea of all of them is like this (using the hardcoded string for clarity):

This is actually quite a tricky problem... But after giving it some thought, here's a clever approach I came up with. It may not be the most

compact(one-liner) solution; but it's quite instructive, could easily be rewritten in any language, and is non-wasteful.Start by recognising that, given an input string of length

`n`

, there are`n-1`

possible places to insert a space. So, all we need to do is:all possible combinationsof those`n-1`

positions, thenFor part (1), I used a simple algorithm to generate the

powersetof`(1..n-1).to_a`

, where`n`

is the input string length:For example:

Now, we can simply insert spaces to the original string at those indexes. One small trick I added is by starting at the

largerindex, it doesn't mess up the other indexes - i.e. you need to use each list indescending order.Here's the final code:

Usage:

Here are some comparisons between the different methods:

Results

Using a longer string:

Here's another way (stuffing spaces into the string).