Skip to content

Instantly share code, notes, and snippets.

@bgnori
Last active August 29, 2015 13:56
Show Gist options
  • Save bgnori/9212027 to your computer and use it in GitHub Desktop.
Save bgnori/9212027 to your computer and use it in GitHub Desktop.
package main
import (
"code.google.com/p/go-tour/tree"
"fmt"
)
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
subWalk(t, ch)
close(ch)
}
func subWalk(t *tree.Tree, ch chan int) {
if t.Left != nil {
subWalk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
subWalk(t.Right, ch)
}
}
func zip(ch1, ch2 chan int, out chan bool) {
var v1, v2 int
var ok1, ok2 bool
for {
select {
case v1, ok1 = <-ch1:
if !ok1 {
close(out)
return
}
v2, ok2 = <-ch2
if !ok2 {
close(out)
return
}
case v2, ok2 = <-ch2:
if !ok2 {
close(out)
return
}
v1, ok1 = <-ch1
if !ok1 {
close(out)
return
}
}
out <- v1 == v2
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int, 100)
ch2 := make(chan int, 100)
ch3 := make(chan bool, 100)
go Walk(t1, ch1)
go Walk(t2, ch2)
go zip(ch1, ch2, ch3)
for v := range ch3 {
if !v {
return false
}
}
return true
}
func main() {
if Same(tree.New(10), tree.New(10)) {
fmt.Println("yay")
} else {
fmt.Println("oh...")
}
}
yay
Program exited.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment