Skip to content

Instantly share code, notes, and snippets.

@andrewmeissner
Last active February 16, 2021 20:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewmeissner/c15e49383d1efe6c40539dfc0ea7dfbe to your computer and use it in GitHub Desktop.
Save andrewmeissner/c15e49383d1efe6c40539dfc0ea7dfbe to your computer and use it in GitHub Desktop.
Golang powerset implementation
// BROKEN - 18 MARCH 2020 - 1,2,3,4,5 PRODUCES INCORRECT RESULTS
package main
import "fmt"
func main() {
powerset := powerSet([]string{"1", "2", "3", "4"})
fmt.Println(powerset)
}
func powerSet(hosts []string) [][]string {
var powerset [][]string
for _, host := range hosts {
tmp := []string{host}
for _, ps := range powerset {
ps = append(ps, host)
powerset = append(powerset, ps)
}
powerset = append(powerset, tmp)
}
return powerset
}
// prints: [[1] [1 2] [2] [1 3] [1 2 3] [2 3] [3] [1 4] [1 2 4] [2 4] [1 3 4] [1 2 3 4] [2 3 4] [3 4] [4]]
@prosticoco
Copy link

Thanks I tried it as an utility function for some code and ran into undefined behaviour, try using {1,2,3,4,5} and see what happens ;)

@andrewmeissner
Copy link
Author

yikes - [1 2 3 5 5] 👎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment