Created
May 2, 2014 17:51
-
-
Save sorah/bbc59707a853928a6c63 to your computer and use it in GitHub Desktop.
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
// http://tour.golang.org/#72 | |
package main | |
import "code.google.com/p/go-tour/tree" | |
import "fmt" | |
// Walk walks the tree t sending all values | |
// from the tree to the channel ch. | |
func Walk(t *tree.Tree, ch chan int) { | |
if t == nil { | |
return | |
} | |
ch <- t.Value | |
Walk(t.Left, ch) | |
Walk(t.Right, ch) | |
} | |
// Same determines whether the trees | |
// t1 and t2 contain the same values. | |
func Same(t1, t2 *tree.Tree) bool { | |
ch1, ch2 := make(chan int), make(chan int) | |
qch := make(chan bool) | |
counts := make(map[int]int) | |
go Workout(t1, ch1) | |
go Workout(t2, ch2) | |
go Counter(counts, ch1, qch) | |
go Counter(counts, ch2, qch) | |
_ = <-qch | |
_ = <-qch | |
for _, v := range counts { | |
if v != 2 { | |
return false | |
} | |
} | |
return true | |
} | |
func Workout(t *tree.Tree, ch chan int) { | |
Walk(t, ch) | |
close(ch) | |
} | |
func Counter(counts map[int]int, ch chan int, qch chan bool) { | |
for v := range ch { | |
//fmt.Println("2: ", v) | |
counts[v] += 1 | |
} | |
qch <- true | |
} | |
func main() { | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
こんなかんじ?
https://gist.github.com/draftcode/eb4c9cff6dec9096eacf
Workoutぐらいの関数だったらinlineにしてしまうかなぁ