Skip to content

Instantly share code, notes, and snippets.

@wperron
Created October 5, 2021 13:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/4eea564faeb4c220ad3aa3526c13cbee to your computer and use it in GitHub Desktop.
Save wperron/4eea564faeb4c220ad3aa3526c13cbee to your computer and use it in GitHub Desktop.
Distinct Permutations
package main
import (
"fmt"
)
func main() {
permuts := distinctPermutations([]int{1, 2, 2, 3, 4}, 3)
fmt.Println(permuts)
}
func distinctPermutations(elems []int, l int) [][]int {
m := map[int]bool{}
set := make([]int, 0, len(elems))
for _, i := range elems {
if _, ok := m[i]; !ok {
m[i] = true
set = append(set, i)
}
}
acc := [][]int{{}}
sl := len(set)
// outer loop for the desired length of each combination
for i := 0; i < l; i++ {
newAcc := [][]int{}
// iterate over each element of the accumulator
for _, curr := range acc {
cp := make([]int, len(curr))
copy(cp, curr)
// iterate over each element of the original set
for j := 0; j < sl; j++ {
nr := append(cp, set[j])
newAcc = append(newAcc, nr)
}
}
acc = newAcc
}
return acc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment