Skip to content

Instantly share code, notes, and snippets.

@koonix
Last active October 6, 2024 17:35
Show Gist options
  • Save koonix/b3c8e9a87b1733894bd168009cb188bf to your computer and use it in GitHub Desktop.
Save koonix/b3c8e9a87b1733894bd168009cb188bf to your computer and use it in GitHub Desktop.
Go function that returns the subsets of a slice.
func subsets[T any](v []T) [][]T {
switch len(v) {
case 0:
return [][]T{
{},
}
case 1:
return [][]T{
{v[0]},
{},
}
}
result := make([][]T, 0, power(2, len(v)))
sub := subsets(v[1:])
for _, s := range sub {
result = append(result, append([]T{v[0]}, s...))
}
result = append(result, sub...)
return result
}
func power(x, y int) int {
switch y {
case 0:
return 1
case 1:
return x
}
for i := 2; i <= y; i++ {
x *= x
}
return x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment