GoLang: Full Permutation Command Line Tool


Let’s program a commline line tool using GoLang. And we take the first parameter and perform a full permutation on it – then it outputs each permutation line by line.

The string in GoLang is immutable – thus we convert it to byte array and then we can swap two characters in the Recursion.

// perm.go
package main

import (
	"fmt"
	"os"
)

func perm(s []byte, idx int) {
	if idx == len(s) {
		fmt.Println(string(s))
		return
	}
	for i := idx; i < len(s); i++ {
		s[i], s[idx] = s[idx], s[i]
		perm(s, idx+1)
		s[i], s[idx] = s[idx], s[i]
	}
}

func main() {
	if len(os.Args) != 2 {
		os.Exit(0)
	}
	perm([]byte(os.Args[1]), 0)
}
$ go run perm.go 123
123
132
213
231
321
312

Full Permutation Algorithms:

–EOF (The Ultimate Computing & Technology Blog) —

319 words
Last Post: Teaching Kids Programming - Sum of Distinct Positive Factorial Numbers
Next Post: Teaching Kids Programming - Sum of Distinct Positive Factorial Numbers via Depth First Search Algorithm

The Permanent URL is: GoLang: Full Permutation Command Line Tool (AMP Version)

Leave a Reply