Created
December 18, 2015 10:33
-
-
Save FedericoPonzi/75ef3dd4db23bc09f8fb to your computer and use it in GitHub Desktop.
Sum of the elements of an array using multithreading and dividi et impera in Golang.
This file contains hidden or 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" | |
func dividiEtImpera( arr []int, low int, hi int, ch chan int){ | |
if hi - low == 1{ | |
// fmt.Println("low: ", low, " hi:", hi, " Caso hi-low==1, ritorno:",arr[hi-1], "+", arr[low] | |
ch <- arr[hi-1] + arr[low] | |
} else if hi-low == 0{ | |
// fmt.Println("low: ", low, " hi:", hi," Caso hi-low==0, ritorno:",arr[low]) | |
ch <- arr[low] | |
}else{ | |
half := int( (low+hi)/2 ) | |
// fmt.Println("low: ", low, " hi:", hi, " half: ",half) | |
ch1, ch2 := make(chan int), make(chan int) | |
go dividiEtImpera(arr, low, half, ch1) | |
go dividiEtImpera(arr, half+1, hi, ch2) | |
firstHalf, secondHalf := <- ch1, <- ch2 | |
// fmt.Println("firsthalf: ", firstHalf, " secondhalf:", secondHalf) | |
ch <- (firstHalf+secondHalf) | |
} | |
} | |
func main(){ | |
var arr = []int{1, 2, 3, 4, 5, 6} | |
ch := make(chan int, 1) | |
dividiEtImpera(arr, 0, len(arr)-1, ch) | |
fmt.Println("The sum of:",arr,"is:", <- ch) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment