Created
March 11, 2024 06:25
-
-
Save prashant-shahi/169ca4d4527ddd826f8d755ef380419e to your computer and use it in GitHub Desktop.
Array sum using Loop, Goroutines and Recursion in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
const ( | |
BATCH_COUNT = 5 | |
) | |
func loopSum(s []int) int { | |
sum := 0 | |
for _, v := range s { | |
sum += v | |
} | |
return sum | |
} | |
func sum(s []int, c chan int) { | |
sum := 0 | |
for _, v := range s { | |
sum += v | |
} | |
c <- sum // send sum to c | |
} | |
func channelSum(s []int) int { | |
c := make(chan int) | |
numberOfSumBatch := len(s)/BATCH_COUNT | |
for i := 0; i < numberOfSumBatch; i++ { | |
go sum(s[i*BATCH_COUNT:(i+1)*BATCH_COUNT], c) | |
} | |
chanSum := 0 | |
for i := 0; i < numberOfSumBatch; i++ { | |
chanSum += <-c // receive from c | |
} | |
return chanSum | |
} | |
func recursiveSum(s []int) int { | |
if len(s) == 0 { | |
return 0 | |
} | |
return s[0] + recursiveSum(s[1:]) | |
} | |
func main() { | |
s := []int{1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393} | |
fmt.Println("Sum from channel: ", channelSum(s)) | |
fmt.Println("Sum from loop: ", loopSum(s)) | |
fmt.Println("Sum from recursive: ", recursiveSum(s)) | |
} | |
// Output: | |
// Sum from channel: 317809 | |
// Sum from loop: 317809 | |
// Sum from recursive: 317809 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment