Permutations using channel

Hello. I am trying to understand how to work with channels on the example
the problem of obtaining permutations.
I took as a basis the code here and almost managed to change it.
However, the program does not work as I expect.
Here is my code:

    package main
    
    import "fmt"
    
    func Generate(alphabet string, length int) chan string {
    	c := make(chan string)
    
    	go func(c chan string) {
    		defer close(c)
    		CreatePermute(c, alphabet, length)
    	}(c)
    
    	return c
    }
    
    func CreatePermute(c chan string, alphabet string, length int) {
    
    	if length == 0 {
    		return
    	}
    	for _, v := range alphabet {
    		c <- string(v)
    		for Y := range Generate(alphabet, length-1) {
    			c <- string(v) + Y
    		}
    	}
    }
    
    func main() {
    	for perm := range Generate("abc", 2) {
    		fmt.Println(perm)
    	}

}

playground

My questions:

  1. Why does the program stops working, if comment out 22 line (c <- string(v))
  2. How fix this?
    I would appreciate for any help.

The program works by having Generate() for a given alphabet delegate a portion of the work to another Generate() call with a shorter alphabet. Consider what happens at line 22-25 when the alphabet is just one character long, and what happens when you remove line 22.

The length parameter seems a bit misguided though, and should probably just be len(alphabet), with the the actual alphabet being reduced for each level. That avoids the current bug the program has with the initial call being with “abc” but length 2, thus not generating any three letter permutations.

Thanks for the quick reply, I have found a mistake. It was necessary to send a message to the channel when length = 0:

...
	if length==0 {
		c <- ""
		return
	}
...

Then everything is working correctly.I’m still not used to thinking on Go =)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.