You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.4 KiB
Go
66 lines
1.4 KiB
Go
package arrays
|
|
|
|
func Sum(a []int) int {
|
|
sum := 0
|
|
|
|
//aternatively
|
|
// for i := 0; i < 5; i++ {
|
|
// sum += a[i]
|
|
// }
|
|
|
|
// OR
|
|
|
|
// for i := range a {
|
|
// sum += a[i]
|
|
// }
|
|
|
|
// OR
|
|
|
|
for _, v := range a {
|
|
sum += v
|
|
}
|
|
return sum
|
|
}
|
|
|
|
// The ... in the method signature means it's variadic function
|
|
// meaning it takes a variable number of arguments
|
|
|
|
// SumAll
|
|
func SumAll(numbersToSum ...[]int) []int {
|
|
// 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
|
|
}
|