Skip to content

Instantly share code, notes, and snippets.

@javi830810
Created October 20, 2020 01:44
Show Gist options
  • Save javi830810/2d04e91ace3f3a688dd39eb3bc2201e0 to your computer and use it in GitHub Desktop.
Save javi830810/2d04e91ace3f3a688dd39eb3bc2201e0 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math"
"strconv"
)
func formatZeros(binary string, total int) string {
temp := binary
for i := 0; i < total-len(binary); i++ {
temp = "0" + temp
}
return temp
}
func toBinary(n int) string {
return strconv.FormatInt(int64(n), 2)
}
func subsets(set []int) [][]int {
setSize := len(set)
var sets [][]int
for i := 0; i < int(math.Pow(2, float64(setSize))); i++ {
var subset []int
for index, c := range formatZeros(toBinary(i), setSize) {
if string(c) == "1" {
subset = append(subset, set[index])
}
}
sets = append(sets, subset)
}
return sets
}
func main() {
set := []int{
1,
2,
3,
4,
5,
}
all := subsets(set)
fmt.Printf("%v \n", all)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment