Last active
October 6, 2024 17:35
-
-
Save koonix/b3c8e9a87b1733894bd168009cb188bf to your computer and use it in GitHub Desktop.
Go function that returns the subsets of a slice.
This file contains 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
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