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
Golang program for implementation of Comb Sort
Golang program for implementation of Binary Search
Golang program to print a matrix in Spiral Format
Golang program for implementation of Floyd–Warshall Algorithm
Golang program for implementation of ZigZag Matrix
Golang program for drawing a Cuboid
Golang program for implementation of Rabin-Karp
Golang program for implementation of Linear Search
Golang program to implement Binary Tree
Golang program for implementation LIFO Stack and FIFO Queue