Created
October 5, 2021 13:25
-
-
Save wperron/4eea564faeb4c220ad3aa3526c13cbee to your computer and use it in GitHub Desktop.
Distinct Permutations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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