Golang program to generate number of slices permutations of number entered by user
This program will generate all possible permutation and combination of number entered by user for example if user entered 2 then 1,2 and 2,1.
Example
package main
import (
"fmt"
"os"
"strconv"
)
func rangeSlice(start, stop int) []int {
if start > stop {
panic("Slice ends before it started")
}
xs := make([]int, stop-start)
for i := 0; i < len(xs); i++ {
xs[i] = i + 1 + start
}
return xs
}
func permutation(xs []int) (permuts [][]int) {
var rc func([]int, int)
rc = func(a []int, k int) {
if k == len(a) {
permuts = append(permuts, append([]int{}, a...))
} else {
for i := k; i < len(xs); i++ {
a[k], a[i] = a[i], a[k]
rc(a, k+1)
a[k], a[i] = a[i], a[k]
}
}
}
rc(xs, 0)
return permuts
}
func main() {
if len(os.Args) < 2 {
fmt.Println("Error: Add 1 numeric value ex. go run permutation.go 2")
os.Exit(1)
}
num, err := strconv.Atoi(os.Args[1])
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
noOfPerms := permutation(rangeSlice(0, num))
fmt.Println("Number of Permutation:",len(noOfPerms))
for i := 0; i < len(noOfPerms); i++ {
fmt.Println(noOfPerms[i])
}
}
Output
Number of Permutation: 24
[1 2 3 4]
[1 2 4 3]
[1 3 2 4]
[1 3 4 2]
[1 4 3 2]
[1 4 2 3]
[2 1 3 4]
[2 1 4 3]
[2 3 1 4]
[2 3 4 1]
[2 4 3 1]
[2 4 1 3]
[3 2 1 4]
[3 2 4 1]
[3 1 2 4]
[3 1 4 2]
[3 4 1 2]
[3 4 2 1]
[4 2 3 1]
[4 2 1 3]
[4 3 2 1]
[4 3 1 2]
[4 1 3 2]
[4 1 2 3]
C:\golang\example>go run permutation.go 3
Number of Permutation: 6
[1 2 3]
[1 3 2]
[2 1 3]
[2 3 1]
[3 2 1]
[3 1 2]
Most Helpful This Week
Empty Interface Type in Go Programming Language
How do you handle HTTP responses in Go?
How to convert Boolean Type to String in Go?
Various examples of printing and formatting in Golang
Nested Struct Type
How do you handle HTTP client server alerting in Go?
How do you read headers in an HTTP response in Go?
How do you create an HTTP server in Go?
Golang program for implementation of Comb Sort
How to get first and last element of slice in Golang?