您的老师已经暗示您应该使用频道而不是返回大数组。通过这样解决,您将不必存储包含所有组合的大数据块,而只需为函数提供不同的迭代并一次处理它们即可。
我们可以看到您的老师提示,
GenerateCombinations返回a
chan string而不是a
[]string:
func GenerateCombinations(alphabet string, length int) <-chan string
这也意味着该函数必须1)创建要返回的通道,以及2)启动将例程传递给该通道的goroutine。该函数如下所示:
func GenerateCombinations(alphabet string, length int) <-chan string { c := make(chan string) // Starting a separate goroutine that will create all the combinations, // feeding them to the channel c go func(c chan string) { defer close(c) // once the iteration function is finished, we close the channel // This is where the iteration will take place // Your teacher's pseudo pre uses recursion // which mean you might want to create a separate function // that can call itself. }(c) return c // Return the channel to the calling function}虽然我将实际迭代留给您,但每个循环都应导致您将组合字符串放入通道中。因为它不是缓冲通道,所以迭代函数将等待主函数读取该值,然后再继续处理下一个迭代。
包含主要功能的游乐场版本:http :
//play.golang.org/p/CBkSjpmQ0t
使用递归的完整的工作解决方案:http :
//play.golang.org/p/0bWDCibSUJ



