diff --git a/day400/problem.go b/day400/problem.go new file mode 100644 index 0000000..b6f05c0 --- /dev/null +++ b/day400/problem.go @@ -0,0 +1,13 @@ +package day149 + +// SumSublist returns the sum of the sublist from start (inclusive) +// up to end (exclusive). +// Runs in O(end-start). +func SumSublist(l []int, start, end int) int { + var sum int + for i := start; i < end; i++ { + sum += l[i] + } + + return sum +} diff --git a/day400/problem_test.go b/day400/problem_test.go new file mode 100644 index 0000000..6d4e64b --- /dev/null +++ b/day400/problem_test.go @@ -0,0 +1,30 @@ +package day149 + +import "testing" + +// nolint +var testcases = []struct { + L []int + start, end int + expected int +}{ + {[]int{1, 2, 3, 4, 5}, 1, 3, 5}, +} + +func TestSumSublist(t *testing.T) { + t.Parallel() + + for _, tc := range testcases { + if result := SumSublist(tc.L, tc.start, tc.end); result != tc.expected { + t.Errorf("Expected %v got %v", tc.expected, result) + } + } +} + +func BenchmarkSumSublist(b *testing.B) { + for i := 0; i < b.N; i++ { + for _, tc := range testcases { + SumSublist(tc.L, tc.start, tc.end) + } + } +}