你的老师已经暗示你应该使用通道而不是返回一个大数组。通过这样解决它,您将不必存储包含所有组合的这一大块数据,而是为您的函数提供不同的迭代并一次处理它们。
我们可以看到你们的老师暗示GenerateCombinations
返回一个chan string
而不是一个[]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 code 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/CBkSjpmQ0t
使用递归的完整工作解决方案:http://play.golang.org/p/0bWDCibSUJ http://play.golang.org/p/0bWDCibSUJ