sum: add SumAllTails

This commit is contained in:
vinchent 2024-09-10 21:51:21 +02:00
parent 4bfd9eda4f
commit 42aaff6c2e
2 changed files with 34 additions and 0 deletions

View File

@ -18,3 +18,17 @@ func SumAll(numbersToSum ...[]int) []int {
return res
}
func SumAllTails(numbersToSum ...[]int) []int {
res := make([]int, len(numbersToSum))
for i, numbers := range numbersToSum {
if len(numbers) == 0 {
res[i] = 0
continue
}
res[i] = Sum(numbers[1:])
}
return res
}

View File

@ -26,3 +26,23 @@ func TestSumAll(t *testing.T) {
t.Errorf("got %d, expected %d", got, exp)
}
}
func TestSumAllTails(t *testing.T) {
t.Run("make the sums of some slices", func(t *testing.T) {
got := SumAllTails([]int{1, 2}, []int{0, 9})
exp := []int{2, 9}
if !slices.Equal(got, exp) {
t.Errorf("got %d, expected %d", got, exp)
}
})
t.Run("safely sum empty slices", func(t *testing.T) {
got := SumAllTails([]int{}, []int{3, 4, 5})
exp := []int{0, 9}
if !slices.Equal(got, exp) {
t.Errorf("got %d, expected %d", got, exp)
}
})
}