Last active
February 16, 2021 20:32
-
-
Save andrewmeissner/c15e49383d1efe6c40539dfc0ea7dfbe to your computer and use it in GitHub Desktop.
Golang powerset implementation
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
// 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]] |
yikes - [1 2 3 5 5] 👎
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ;)