Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add problem 4 of chapter 8 #10

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/chapter8/problem4.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package chapter8

// PowerSet returns all subset of give set
func PowerSet(set []int) [][]int {
if len(set) == 0 {
return [][]int{
[]int{},
}
}

var res [][]int
for _, subset := range PowerSet(set[1:]) {
res = append(res, subset, append(subset, set[0]))
}

return res
}
84 changes: 84 additions & 0 deletions src/chapter8/problem4_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package chapter8

import (
"reflect"
"testing"
)

func TestPowerSet(t *testing.T) {
tests := map[string]struct {
in []int
out [][]int
}{

"Should return empty subset when input is empty": {
in: []int{},
out: [][]int{
[]int{},
},
},

"Should return 2 subsets when input's length is 1": {
in: []int{1},
out: [][]int{
[]int{},
[]int{1},
},
},

"Should return 4 subsets when input's length is 2": {
in: []int{1, 2},
out: [][]int{
[]int{},
[]int{1},
[]int{2},
[]int{2, 1},
},
},

"Should return 8 subsets when input's length is 3": {
in: []int{1, 2, 3},
out: [][]int{
[]int{},
[]int{1},
[]int{2},
[]int{2, 1},
[]int{3},
[]int{3, 1},
[]int{3, 2},
[]int{3, 2, 1},
},
},

"Should return 16 subsets when input's length is 4": {
in: []int{1, 2, 3, 4},
out: [][]int{
[]int{},
[]int{1},
[]int{2},
[]int{2, 1},
[]int{3},
[]int{3, 1},
[]int{3, 2},
[]int{3, 2, 1},
[]int{4},
[]int{4, 1},
[]int{4, 2},
[]int{4, 2, 1},
[]int{4, 3},
[]int{4, 3, 1},
[]int{4, 3, 2},
[]int{4, 3, 2, 1},
},
},
}

for k, test := range tests {
t.Run(k, func(t *testing.T) {
out := PowerSet(test.in)
if !reflect.DeepEqual(out, test.out) {
t.Errorf("actual=%#v expected=%#v", out, test.out)
}
})
}
}