Skip to content

Instantly share code, notes, and snippets.

@akhenakh
Created January 9, 2023 18:43
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 akhenakh/a5ed595f1530beda1ec8404aa4e53342 to your computer and use it in GitHub Desktop.
Save akhenakh/a5ed595f1530beda1ec8404aa4e53342 to your computer and use it in GitHub Desktop.
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