Finished up arrays and slice lesson

drew/sql-it
Drew Bednar 11 months ago
parent 7a95cd68f1
commit eeef9622df

@ -1,3 +1,3 @@
module myarray
module arrays
go 1.21.0

@ -27,5 +27,39 @@ func Sum(a []int) int {
// SumAll
func SumAll(numbersToSum ...[]int) []int {
return nil
// lengthOfNumbers := len(numbersToSum)
//There's a new way to create a slice. make allows you to create a slice with a starting capacity of the len of the numbersToSum we need to work through.
// sums := make([]int, lengthOfNumbers)
// for i, numbers := range numbersToSum {
// sums[i] = Sum(numbers)
// }
// Using the append method you do not have to worry about capacity and index errors
// append will create a new slice with greater capacity and the new value added to it.
// The is a different between len() and capacity() capacity is the allocated size, and there
// is an algorithm used by append to determine when it needs to change.
var sums []int
for _, numbers := range numbersToSum {
sums = append(sums, Sum(numbers))
}
return sums
}
func SumAllTails(numbersToSum ...[]int) []int {
var sums []int
for _, numbers := range numbersToSum {
if len(numbers) == 0 {
sums = append(sums, 0)
} else {
tails := numbers[1:]
sums = append(sums, Sum(tails))
}
}
return sums
}

@ -81,3 +81,29 @@ func TestSumAll(t *testing.T) {
t.Errorf("Using slices.Equal got %v expected %v given", got, expected)
}
}
// The tail of a collection is all items in the collection except the first one (the "head").
func TestSumAllTails(t *testing.T) {
// Another example of helper function
checkSums := func(t testing.TB, got, want []int) {
t.Helper()
if !reflect.DeepEqual(got, want) {
t.Errorf("got %v want %v", got, want)
}
}
t.Run("test slices of same lenght", func(t *testing.T) {
got := SumAllTails([]int{1, 2}, []int{0, 9})
want := []int{2, 9}
checkSums(t, got, want)
})
t.Run("test an empty slice and slice of different len", func(t *testing.T) {
got := SumAllTails([]int{}, []int{0, 4, 5})
want := []int{0, 9}
checkSums(t, got, want)
})
}

Loading…
Cancel
Save