Sahak 12
Sahak 12

Reputation: 33

Find all array permutations of splitting a string in C+++

I have a string of numbers that I'd like to split into all possible combinations (the order of letters must be remain fixed), so that:

data = "12479"

Output

combs = [[1, 2479], [1, 2, 479], [1, 24, 79] ...etc]

How can I do that?

Upvotes: 1

Views: 154

Answers (1)

user9706
user9706

Reputation:

The recursive algorithm is straight forward:

combinations(data)
  if size(data) == 0 return []
  if size(data) == 1 return [ data ]
  return
     [ head(data) ] + combinations(tail(data)) +
     [ head(data) + head(combinations(tail(data))) + tail(combinations(tail(data)))

The first two return statement are base cases. The 3rd return statement either split the first element off or doesn't. Note that +, head or tail operate either on arrays or strings depending on context.

Upvotes: 1

Related Questions