2

I'm trying to generate incremental combinations from a string, like:

// for "23405"
2
3
4
5
23
34
40
05
234
340
405
2340
3405
23405

I'm doing it with nested loops:

str := "23405"
for i := 0; i <= len(str); i++ {
    for j := 0; j <= i; j++ {
        fmt.Println(str[j:i])
    }
}

Is it possible to do the same with recursive function? I'm writing it with go but an example in any language would be helpful. Here's the playground link.

1
  • What about using a generator within Python ? Commented Dec 9, 2016 at 4:57

1 Answer 1

2

Here's my attempt of recursion: https://repl.it/ElYY/9

package main

import "fmt"

func reverse(str string, length int, i int) {
  if len(str) > length+i && length > 0 {
    fmt.Println(str[i:length+i])
    reverse(str, length, i+1)
  } else if len(str) == length+i && length > 0 {
    fmt.Println(str[i:length+i])
    reverse(str, length-1, 0)
  }
}

func recIterate(str string, length int, i int) {
  if length > i {
    fmt.Println(str[i:len(str)-length+i+1])
    recIterate(str, length, i+1)
  } else if length == i && length > 0{
    recIterate(str, length-1, 0)
  }
}

func main() {
  str := "234051234"
  recIterate(str, len(str), 0)
  // reverse(str, len(str), 0)
}

Shout out to nexus66 for helping~

Sign up to request clarification or add additional context in comments.

5 Comments

Why there is a lot of empty spaces at the end ?
If you want, look at the correct output here and try to improve your code.
@nexus66 Found it. Was still going through it when length = 0
Yes but still your output is reversed :-) try to give the same output like the OP wants to have.
@nexus66 Added it as a separate method :D Sorry for the delay, had lunch.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.