-
-
Save minikomi/2909603 to your computer and use it in GitHub Desktop.
Pascal's triangle using channels and goroutines
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" | |
func worker(row int, input chan int, output chan int, done chan int) { | |
display := "" | |
previous := 0 | |
for i := 0; i < row+1; i++ { | |
read := <-input | |
display += fmt.Sprintf("%d ", read) | |
output <- read + previous | |
previous = read | |
} | |
fmt.Println(display) | |
output <- 1 // next row has one more element, let's send it | |
done <- 1 | |
} | |
func main() { | |
rows := 6 | |
cmd := make([]chan int, rows+1) | |
for i := 0; i < rows+1; i++ { | |
cmd[i] = make(chan int, rows+1) | |
} | |
done := make(chan int, rows) | |
cmd[0] <- 1 | |
for i := 0; i < rows; i++ { | |
go worker(i, cmd[i], cmd[i+1], done) | |
} | |
for i := 0; i < rows; i++ { | |
<-done | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment