用 go channel 实现素数迭代器、二叉查找树比较

栏目: Go · 发布时间: 6年前

内容简介:这是罗凯同学内部《Go 快速入门》课程第五讲的作业。第一题:使用 channel 完成打印1000以内的素数第二题:等价二叉查找树,来自 Go tour:

这是罗凯同学内部《Go 快速入门》课程第五讲的作业。

第一题:使用 channel 完成打印1000以内的素数

package main

import "fmt"

func prime(c chan<- int) {
    i := 2
    for {
        isPrime := true
        for j := 2; j < i; j += 1 {
            if i % j == 0 {
                isPrime = false
            }
        }
        if isPrime {
            c <- i
        }
        i += 1
    }
}

func main() {
    c := make(chan int)
    go prime(c)
    for {
        p := <-c
        if p >= 1000 {
            break
        }
        fmt.Println(p)
    }
}

第二题:等价二叉查找树,来自 Go tour: https://tour.go-zh.org/concurrency/7

原题使用 tree.New(1) 来生成一个包含10个元素的二叉查找树,简单的实现可以基于这一点,正好从channel里读出10个数字。

以下这个版本的实现更复杂一些,不假定二叉查找树的长度,所以加一个 wrapper,用来 close channel 。

package main

import (
    "fmt"
    "golang.org/x/tour/tree"
)

// Walk 步进 tree t 将所有的值从 tree 发送到 channel ch。
func Walk(t *tree.Tree, ch chan int) {
    if t == nil {
        return
    }
    Walk(t.Left, ch)
    ch <- t.Value
    Walk(t.Right, ch)
}

func WalkWrapper(t *tree.Tree, ch chan int) {
    Walk(t, ch)
    close(ch)
}

// Same 检测树 t1 和 t2 是否含有相同的值。
func Same(t1, t2 *tree.Tree) bool {
    c1 := make(chan int)
    c2 := make(chan int)
    go WalkWrapper(t1, c1)
    go WalkWrapper(t2, c2)
    for {
        v1, ok1 := <-c1
        v2, ok2 := <-c2

        if ok1 == false && ok2 == false {
            return true
        } else if ok1 == false || ok2 == false {
            return false
        } else {
            if v1 != v2 {
                return false
            }
        }
    }
}

func main() {
    t1 := &tree.Tree{&tree.Tree{nil, 1, nil}, 2, &tree.Tree{nil, 3, nil}}
    t2 := &tree.Tree{&tree.Tree{&tree.Tree{nil, 1, nil}, 2, nil}, 3, &tree.Tree{nil, 4, nil}}
    fmt.Println(t1)
    fmt.Println(t2)
    fmt.Println(Same(t1, t2))

    t3 := tree.New(1)
    t4 := tree.New(1)
    fmt.Println(t3)
    fmt.Println(t4)
    fmt.Println(Same(t3, t4))
}

转载请注明出自,如是转载文则注明原出处,谢谢:)

RSS订阅地址: http://www.felix021.com/blog/feed.php


以上所述就是小编给大家介绍的《用 go channel 实现素数迭代器、二叉查找树比较》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Data Mining

Web Data Mining

Bing Liu / Springer / 2006-12-28 / USD 59.95

Web mining aims to discover useful information and knowledge from the Web hyperlink structure, page contents, and usage data. Although Web mining uses many conventional data mining techniques, it is n......一起来看看 《Web Data Mining》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具