https://play.golang.org/p/cS7S3tYAXrn
The recursive function permute()
works when passed a slice of 6 unique ints, but fails when passed 7 or more ints.
Where am I going wrong?
Code duplicated here:
package main
import (
"fmt"
"strconv"
"strings"
)
// recursive function that returns all possible permutations of the given input ([]int)
func permute(prefix []int, input []int) [][]int {
if len(input) == 0 {
return [][]int{prefix}
}
// fmt.Println("permute", prefix, input)
var res [][]int
for i := range input {
// cc := copy(input)
cc := make([]int, len(input))
copy(cc, input) // builtin
if i > 0 {
cc[0], cc[i] = cc[i], cc[0]
}
newprefix := append(prefix, cc[0])
p := permute(newprefix, cc[1:])
res = append(res, p...)
// fmt.Println(" append", prefix, p)
}
// fmt.Println(" res", prefix, res)
return res
}
// use a map to count the no of occurrences of each permutation
// input: [] of permutations ([]int)
func checkdup(input [][]int) {
m := make(map[string]int)
for _, n := range input {
var s []string
for _, i := range n {
s = append(s, strconv.Itoa(i))
}
key := strings.Join(s, "-")
m[key]++
}
fmt.Printf("%d in the map, %d unique\n", len(input), len(m))
}
// returns the factorial of n
func factorial(n int) int {
i := n
for i > 1 {
i--
n = n * i
}
return n
}
func main() {
a := []int{1, 2, 3, 4, 5, 6, 7}
fmt.Println("permute 6 (6! is", factorial(6), ")")
p = permute(nil, a[:6])
checkdup(p)
fmt.Println("permute 7 (7! is", factorial(7), ")")
p = permute(nil, a[:7])
checkdup(p)
}