Skip to content

Instantly share code, notes, and snippets.

@jooyunghan
Forked from anonymous/ant.go
Created March 1, 2016 08:34
Show Gist options
  • Save jooyunghan/6e043965370d03f1c188 to your computer and use it in GitHub Desktop.
Save jooyunghan/6e043965370d03f1c188 to your computer and use it in GitHub Desktop.
Look and say sequence in Go using Chan/Goroutine
package main
import "fmt"
type genf func(chan<- uint8)
func gen(f genf) <-chan uint8 {
c := make(chan uint8)
go f(c)
return c
}
type wrapf func(<-chan uint8, chan<- uint8)
func wrap(in <-chan uint8, f wrapf) <-chan uint8 {
c := make(chan uint8)
go f(in, c)
return c
}
func ant(in <-chan uint8, out chan<- uint8) {
n := <-in
var c uint8 = 1
for m := range in {
if n != m {
out <- c
out <- n
n = m
c = 1
} else {
c += 1
}
}
out <- n
out <- c
close(out)
}
func first(out chan<- uint8) {
out <- 1
close(out)
}
func main() {
m := 1000000
n := 1000000
c := gen(first)
for i := 1; i < m; i++ {
c = wrap(c, ant)
}
for i := 0; i < n; i++ {
<-c
}
fmt.Println(<-c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment