diff --git a/src/chapter8/problem1.go b/src/chapter8/problem1.go new file mode 100644 index 0000000..f003d12 --- /dev/null +++ b/src/chapter8/problem1.go @@ -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] +} diff --git a/src/chapter8/problem1_test.go b/src/chapter8/problem1_test.go new file mode 100644 index 0000000..71165fa --- /dev/null +++ b/src/chapter8/problem1_test.go @@ -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) + } + }) + } +}