The goal of my program is to create the permutations (aka all combinations where order matters and there is no repitition) of items in a given array. The error occurs when using append in the following code:
package main
import (
"fmt"
)
func buildNewPool(arr []int, i int) (s []int) {
s1 := arr[:i]
s2 := arr[i+1:]
s = append(s, s1...)
s = append(s, s2...)
return s
}
func Permutations(value []int, pool []int, n int, chOut chan<- []int) {
if n == 0 {
chOut <- value
}
for i := 0; i < len(pool); i++ {
newValue := append(value,pool[i])
newPool := buildNewPool(pool,i)
newN := n - 1
go Permutations(newValue, newPool, newN, chOut)
}
return
}
func main() {
ch := make(chan []int)
var Nums = []int{1, 2, 3, 4, 5, 6}
var V []int
Permutations(V, Nums, 6, ch)
for i := range ch {
fmt.Println(i)
}
}
It works normally with a small list, but once I go over 5 items in the array, I was getting repeats in my outputted array. To fix this I made my own append function for it and the code is:
package main
import (
"fmt"
)
func buildNewPool(arr []int, i int) (s []int) {
s1 := arr[:i]
s2 := arr[i+1:]
s = append(s, s1...)
s = append(s, s2...)
return s
}
func appendValue(v []int, n int) (value []int) {
s := make([]int, len(v)+1)
copy(s, v)
s[len(s)-1] = n
value = s
return
}
func Permutations(value []int, pool []int, n int, chOut chan<- []int) {
if n == 0 {
chOut <- value
}
for i := 0; i < len(pool); i++ {
newValue := appendValue(value,pool[i])
newPool := buildNewPool(pool,i)
newN := n - 1
go Permutations(newValue, newPool, newN, chOut)
}
return
}
func main() {
ch := make(chan []int)
var Nums = []int{1, 2, 3, 4, 5, 6}
var V []int
Permutations(V, Nums, 6, ch)
for i := range ch {
fmt.Println(i)
}
}
This fixed the issue, but I’m curious about why it occurred in the first place.
A friend also helped me clean up the code and make it use append, and made it use append, but still had to do part of my append function to make it work. Code:
package main
import (
"fmt"
)
func NewPool(arr []int, i int) (s []int) {
s1 := arr[:i]
s2 := arr[i+1:]
s = append(s, s1...)
s = append(s, s2...)
return s
}
func Permutations(value []int, pool []int, n int, chOut chan<- []int) {
if n == 0 {
chOut <- value
}
for i := 0; i < len(pool); i++ {
t := make([]int, len(value))
copy(t, value)
go Permutations(append(t, pool[i]), NewPool(pool, i), n-1, chOut)
}
return
}
func main() {
ch := make(chan []int)
var Nums = []int{1, 2, 3, 4, 5}
var V []int
Permutations(V, Nums, 2, ch)
for i := range ch {
fmt.Println(i)
}
}
Thanks for reading
Main Question: Why did the Append error occur?