stillysmag

tour.golang.org/concurrency/8

Apr 20th, 2021
592
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.   fmt.Println("Walk", name, t.Value)
  13.   ch <- t.Value
  14.   if t.Right != nil {
  15.     Walk(name, t.Right, ch)
  16.   }
  17. }
  18. var tree1 = tree.Tree{
  19.   Left: &tree.Tree{
  20.     Value: 1,
  21.     Right: &tree.Tree{
  22.       Value: 2,
  23.     },
  24.   },
  25.   Value: 3,
  26.   Right: &tree.Tree{
  27.     Left: &tree.Tree{
  28.       Value: 5,
  29.     },
  30.     Value: 8,
  31.   },
  32. }
  33. var tree2 = tree.Tree{
  34.   Left: &tree.Tree{
  35.     Left: &tree.Tree{
  36.       Value: 1,
  37.       Right: &tree.Tree{
  38.         Value: 2,
  39.       },
  40.     },
  41.     Value: 3,
  42.     Right: &tree.Tree{
  43.       Value: 5,
  44.     },
  45.   },
  46.   Value: 8,
  47. }
  48.  
  49. func Same(t1, t2 *tree.Tree) bool {
  50.   var ch1 = make(chan int, 1)
  51.   go Walk("t1", t1, ch1)
  52.  
  53.   var ch2 = make(chan int, 1)
  54.   go Walk("t2", t2, ch2)
  55.  
  56.   for i:= 0; i<5; i++ {
  57.     v1, v2 := <-ch1, <-ch2
  58.     if v1 != v2 {
  59.       return false
  60.     }
  61.   }
  62.   return true
  63. }
  64. func main() {
  65.   result := Same(&tree1, &tree2)
  66.   fmt.Println("result", result)
  67. }
  68.  
  69.  
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.

×