stillysmag

tour.golang.org/concurrency/8-2

Apr 20th, 2021
559
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.   "golang.org/x/tour/tree"
  5.   "fmt"
  6. )
  7.  
  8. func Walk(name string, t *tree.Tree, ch chan int) {
  9.   if t.Left != nil {
  10.     Walk(name, t.Left, ch)
  11.   }
  12.   ch <- t.Value
  13.   if t.Right != nil {
  14.     Walk(name, t.Right, ch)
  15.   }
  16. }
  17. var tree1 = tree.Tree{
  18.   Left: &tree.Tree{
  19.     Value: 1,
  20.     Right: &tree.Tree{
  21.       Value: 2,
  22.     },
  23.   },
  24.   Value: 3,
  25.   Right: &tree.Tree{
  26.     Left: &tree.Tree{
  27.       Value: 5,
  28.     },
  29.     Value: 8,
  30.   },
  31. }
  32. var tree2 = tree.Tree{
  33.   Left: &tree.Tree{
  34.     Left: &tree.Tree{
  35.       Value: 1,
  36.     },
  37.     Value: 2,
  38.     },
  39.   Value: 3,
  40. }
  41.  
  42. func Same(t1, t2 *tree.Tree) bool {
  43.   var ch1 = make(chan int, 1)
  44.   go func() {
  45.     Walk("t1", t1, ch1)
  46.     fmt.Println("close 1")
  47.     close(ch1)
  48.   } ()
  49.  
  50.   var ch2 = make(chan int, 1)
  51.   go func() {
  52.       Walk("t2", t2, ch2)
  53.       fmt.Println("close 2")
  54.       close(ch2)
  55.   } ()
  56.  
  57.   for i:= 0; i<5; i++ {
  58.     v1, ok1 := <-ch1
  59.     v2, ok2 := <-ch2
  60.     if !ok1 || !ok2 || v1 != v2 {
  61.       return false
  62.     }
  63.   }
  64.   return true
  65. }
  66. func main() {
  67.   result := Same(&tree1, &tree2)
  68.   fmt.Println("result", result)
  69. }
  70.  
  71.  
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×