Generation of Strings - generation


I have this code

My idea was to generate all possible combinations pretty much this:


you get the picture I think.

I got this solution but the objective is to simplify the solution without using channels if possible :

package main

import "fmt"

func GenerateCombinations(alphabet string, length int) <-chan string {
	c := make(chan string)

	go func(c chan string) {
		defer close(c)

		AddLetter(c, "", alphabet, length)

	return c

func AddLetter(c chan string, combo string, alphabet string, length int) {
	if length <= 0 {

	var newCombo string
	for _, ch := range alphabet {
		newCombo = combo + string(ch)
		c <- newCombo
		AddLetter(c, newCombo, alphabet, length-1)

func main() {

	list := "abc"

	for combination := range GenerateCombinations(list, 3) {
		if len(combination) == 3 {



This looks suspiciously like homework, so rather than give you an answer, I’ll give you a different way to look at the problem.

Imagine your alphabet of allowed characters was “0123456789” and you called GenerateCombinations(alphabet, 3). What would the output be? Something like:



There’s a fairly simple and obvious way to generate that sequence, right? You could make an array of 3 bytes to hold the 3 digits, and write some code to add 1 repeatedly and print the value each time. You can use the same long addition method you learned in school.

The only trick is that you need a way to convert the character ‘0’ into the value 0, the character ‘1’ into the value 1, and so on. That’s just a matter of counting how far the character is through the alphabet, the string of allowed characters in order.

Now think about how you’d make the code deal with any number base, so that GenerateCombinations("0123456789ABCDEF", 3) would generate all the 3-digit hex numbers.

Converting characters to values they represent is still just a matter of looking through the alphabet string to find them; F represents 15, for example. And when you’re doing the long addition, you have to check if you get a digit value bigger than the length of the alphabet string (15), and if so, you subtract that same value and carry 1 to the left.

Once your code works with hex as well as decimal, you should then find that it works with any alphabet you choose.

In other words, your original example is just like you’re being given the task of writing all the 3-digit numbers in base 3, where the digits are ‘a’, ‘b’ and ‘c’ rather than ‘0’, ‘1’ and ‘2’.

My word is only my word but it is not Homework, dev is not even my field i’m just trying to write my python scripts in golang to get the grasp of the language.

Anyway there you go

OK, well it was quite a fun little exercise. So here’s a Gist with your version, my version, code to call both and print the output to compare, and a benchmark.

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