Created
January 9, 2023 18:43
-
-
Save akhenakh/a5ed595f1530beda1ec8404aa4e53342 to your computer and use it in GitHub Desktop.
Golang combinations (not permutations) source https://www.sobyte.net/post/2022-01/go-slice/ https://go.dev/play/p/QX3svk0XJOV
This file contains 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" | |
"math/bits" | |
) | |
func main() { | |
c := combinations([]string{"A", "B", "C"}, 2) | |
fmt.Println(c) | |
} | |
func combinations(set []string, n int) (subsets [][]string) { | |
length := uint(len(set)) | |
if n > len(set) { | |
n = len(set) | |
} | |
// Go through all possible combinations of objects | |
// from 1 (only first object in subset) to 2^length (all objects in subset) | |
for subsetBits := 1; subsetBits < (1 << length); subsetBits++ { | |
if n > 0 && bits.OnesCount(uint(subsetBits)) != n { | |
continue | |
} | |
var subset []string | |
for object := uint(0); object < length; object++ { | |
// checks if object is contained in subset | |
// by checking if bit 'object' is set in subsetBits | |
if (subsetBits>>object)&1 == 1 { | |
// add object to subset | |
subset = append(subset, set[object]) | |
} | |
} | |
// add subset to subsets | |
subsets = append(subsets, subset) | |
} | |
return subsets | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment