Skip to content

Instantly share code, notes, and snippets.

@panki
Created October 19, 2021 20:40
Show Gist options
  • Save panki/34300453d75af9d705e996e12d7d425a to your computer and use it in GitHub Desktop.
Save panki/34300453d75af9d705e996e12d7d425a to your computer and use it in GitHub Desktop.
package main
import "fmt"
func PrefixSum(my_array,my_output []int ,parent chan int) {
if len(my_array)<2{
parent<-my_array[0]
my_output[0] = my_array[0] + <-parent
}else if len(my_array)<1{
parent<-0
<-parent
}else {
mid:=len(my_array)/2
left:= make(chan int)
right:=make(chan int)
go PrefixSum(my_array[:mid],my_output[:mid],left)
go PrefixSum(my_array[mid:],my_output[mid:],right)
leftsum:=<-left
parent<- leftsum +<-right
fromleft:= <-parent
left<-fromleft
right<-fromleft + leftsum
<-left
<-right
}
parent<-0
}
func main () {
data:= []int{1,2,3,4}
output:= make([]int,len(data))
parent :=make(chan int)
go PrefixSum(data,output,parent)
sum:= <-parent
fromleft:=0
parent<-fromleft
donezero:=<-parent
fmt.Println(data,output,sum,donezero)
}
@panki
Copy link
Author

panki commented Oct 19, 2021

Prefix Sum Problem : A Concurrent Approach
In this lesson, you will study how to write the concurrent solution to the Prefix Sum Algorithm.

The Prefix Sum of an array arr of length n is another array prefixSum_arr of the same length such that the value of the ith index in prefixSum_arr is the sum of all values from arr[0], arr[1]...arr[i].

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment