Created
May 3, 2019 18:51
-
-
Save lowewenzel/5f77bb6d737879ab78fabd6a210a7f48 to your computer and use it in GitHub Desktop.
Linear/2 Sum Function
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" | |
import "math" | |
func CalcSum(numbers []int, left int, right int) int { | |
aFinished := make(chan int) | |
bFinished := make(chan int) | |
mid := int(math.Floor(float64(len(numbers)) / float64(2))) | |
// a reads from index 0 (inclusive) to the middle (exclusive) | |
go func() { | |
asum := 0 | |
for i := left; i < mid; i++ { | |
asum += numbers[i] | |
} | |
aFinished <- asum | |
}() | |
// b reads from index end (inclusive) to the mid | |
go func() { | |
bsum := 0 | |
for i := len(numbers) - 1; i >= mid; i-- { | |
bsum += numbers[i] | |
} | |
bFinished <- bsum | |
}() | |
return <-aFinished + <-bFinished | |
} | |
func main() { | |
numbers := []int{1, 5, 2, 7, 1, 9} | |
fmt.Println(CalcSum(numbers, 0, len(numbers))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment