Skip to content

Commit

Permalink
Add problem 4 of chapter 8
Browse files Browse the repository at this point in the history
  • Loading branch information
motomux committed Feb 25, 2017
1 parent 5666eba commit cb5650e
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
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 main

// 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 main

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)
}
})
}
}

0 comments on commit cb5650e

Please sign in to comment.