diff options
| author | mo khan <mo@mokhan.ca> | 2021-11-21 17:17:12 -0700 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2021-11-21 17:17:12 -0700 |
| commit | c78fc266c31afe75c704d596cb920406086a8187 (patch) | |
| tree | 42567e7e24817a5f4e708155aed3ec5cfffb5407 /exercises/15.1 | |
| parent | b1e754863d9a7cac7ddc2c9e2ba3bc108b764897 (diff) | |
write recursive solution in golang
Diffstat (limited to 'exercises/15.1')
| -rw-r--r-- | exercises/15.1/go.mod | 3 | ||||
| -rw-r--r-- | exercises/15.1/rod_cutting_test.go | 39 |
2 files changed, 42 insertions, 0 deletions
diff --git a/exercises/15.1/go.mod b/exercises/15.1/go.mod new file mode 100644 index 0000000..655ec3d --- /dev/null +++ b/exercises/15.1/go.mod @@ -0,0 +1,3 @@ +module git.mokhan.ca/school/comp-372/exercises/15.1 + +go 1.17 diff --git a/exercises/15.1/rod_cutting_test.go b/exercises/15.1/rod_cutting_test.go new file mode 100644 index 0000000..515a790 --- /dev/null +++ b/exercises/15.1/rod_cutting_test.go @@ -0,0 +1,39 @@ +package main + +import ( + "testing" +) + +func max(x, y int) int { + if x > y { + return x + } + return y +} + +func cutRod(p []int, n int) int { + if n == 0 { + return 0 + } + q := -1 + for i := 1; i <= n; i++ { + q = max(q, p[i]+cutRod(p, n-i)) + } + return q +} + +func TestRodCutting(t *testing.T) { + r := []int{0, 1, 5, 8, 10, 13, 17, 18, 22, 25, 30} + p := []int{0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30} + + t.Run("with recursive approach", func(t *testing.T) { + for n := 0; n < len(p); n++ { + expected := r[n] + actual := cutRod(p, n) + + if expected != actual { + t.Errorf("%d: expected %d, actual %d", n, expected, actual) + } + } + }) +} |
