46 lines
1.2 KiB
Go
46 lines
1.2 KiB
Go
|
package arraysum
|
||
|
|
||
|
// SumWithForLoop uses a for loop to
|
||
|
// calculate the sum of the slice argument.
|
||
|
func SumWithForLoop(numbers []int) int {
|
||
|
output := 0
|
||
|
for _, v := range numbers {
|
||
|
output += v
|
||
|
}
|
||
|
return output
|
||
|
}
|
||
|
|
||
|
// SumWithRecursion uses recursion to
|
||
|
// calculate the sum of the slice argument.
|
||
|
func SumWithRecursion(numbers []int) int {
|
||
|
if len(numbers) == 0 {
|
||
|
return 0
|
||
|
}
|
||
|
|
||
|
return numbers[0] + SumWithRecursion(numbers[1:])
|
||
|
}
|
||
|
|
||
|
// SumWithRecursion uses tail recursion to
|
||
|
// calculate the sum of the slice argument.
|
||
|
func SumWithTailRecursion(numbers []int) int {
|
||
|
return SumWithSubTailCall(numbers, 0)
|
||
|
}
|
||
|
|
||
|
// SumWithSubTailCall is a sub function of
|
||
|
// SumWithTailRecursion. This function takes the
|
||
|
// first element of the array and adds it to the
|
||
|
// running total. It then removes said element and
|
||
|
// calls itself with the updated slice and the current
|
||
|
// running total.
|
||
|
// Recursion ends when there are no more elements in the
|
||
|
// slice. It returns the total sum back to the SubWithTailRecursion
|
||
|
// function.
|
||
|
func SumWithSubTailCall(numbers []int, runningTotal int) int {
|
||
|
if len(numbers) == 0 {
|
||
|
return runningTotal
|
||
|
}
|
||
|
|
||
|
runningTotal += numbers[0]
|
||
|
return SumWithSubTailCall(numbers[1:], runningTotal)
|
||
|
}
|