stillysmag

tour.golang.org/concurrency/8-3

Apr 20th, 2021
705
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(t *tree.Tree, ch chan int) {
  9.   if t.Left != nil {
  10.     Walk(t.Left, ch)
  11.   }
  12.   ch <- t.Value
  13.   if t.Right != nil {
  14.     Walk(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.     Value: 1,
  35.     },
  36.   Value: 2,
  37. }
  38.  
  39. type readChan struct {
  40.     name    string
  41.     closed  bool
  42.     ch      chan int
  43. }
  44. func createChan(name string) *readChan {
  45.     var rc = readChan{
  46.         name: name,
  47.         ch: make(chan int, 1),
  48.     }
  49.     return &rc
  50. }
  51. func (rc *readChan) close() {
  52.     if !rc.closed {
  53.         rc.closed = true
  54.         fmt.Println("close", rc.name)
  55.         close(rc.ch)
  56.     }
  57. }
  58. func (rc *readChan) startWalk(t *tree.Tree) {
  59.     go func() {
  60.         Walk(t, rc.ch)
  61.         rc.close()
  62.     } ()
  63. }
  64.  
  65. func Same(t1, t2 *tree.Tree) bool {
  66.   var ch1 = createChan("c1")
  67.   defer ch1.close()
  68.   ch1.startWalk(t1)
  69.  
  70.   var ch2 = createChan("c2")
  71.   defer ch2.close()
  72.   ch2.startWalk(t2)
  73.  
  74.   for {
  75.     v1, ok1 := <-ch1.ch
  76.     v2, ok2 := <-ch2.ch
  77.     fmt.Println("values:", v1, ok1, v2, ok2)
  78.     if !ok1 || !ok2 || v1 != v2 {
  79.       return !ok1 && !ok2
  80.     }
  81.   }
  82.   return true
  83. }
  84. func main() {
  85.   result := Same(&tree1, &tree2)
  86.   fmt.Println("result", result)
  87. }
  88.  
  89.  
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.

×