Skip to content

Commit

Permalink
Add problem 1 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 94c527d
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/chapter8/problem1.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package chapter8

// TripleStep calles TripleStepR to calculates possible ways to claim
func TripleStep(num int) int {
if num <= 0 {
return 0
}
memo := make([]int, num+1)

return TripleStepR(num, memo)
}

// TripleStepR calculates possible ways to claim give number of stairs with 3, 2, 1 steps
func TripleStepR(num int, memo []int) int {
if num < 0 {
return 0
} else if num == 0 {
return 1
}

if memo[num] == 0 {
memo[num] = TripleStepR(num-3, memo) +
TripleStepR(num-2, memo) +
TripleStepR(num-1, memo)
}

return memo[num]
}
40 changes: 40 additions & 0 deletions src/chapter8/problem1_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package chapter8

import "testing"

func TestTripleStep(t *testing.T) {
tests := map[string]struct {
in int
out int
}{
"Num is 0": {
in: 0,
out: 0,
},
"Num is 1": {
in: 1,
out: 1,
},
"Num is 2": {
in: 2,
out: 2,
},
"Num is 3": {
in: 3,
out: 4,
},
"Num is 5": {
in: 5,
out: 13,
},
}

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

0 comments on commit 94c527d

Please sign in to comment.