《GO语言圣经》读书笔记 第二章 习题解答

练习 2.1: 向tempconv包添加类型、常量和函数用来处理Kelvin绝对温度的转换,Kelvin 绝对零度是−273.15°C,Kelvin绝对温度1K和摄氏度1°C的单位间隔是一样的


package tempconv

import "fmt"

type Celsius float64
type Fahrenheit float64
type Kelvin float64

const (
    AbsoluteZeroC Celsius = -273.15
    FreezingC Celsius = 0
    BoilingC Celsius = 100
)

func (c Celsius) String() string    { return fmt.Sprintf("%g°C", c) }
func (f Fahrenheit) String() string { return fmt.Sprintf("%g°F", f) }
func (k Kelvin) String() string     { return fmt.Sprintf("%gK", k) }

func CToF(c Celsius) Fahrenheit { return Fahrenheit(c*9/5 + 32) }
func FToC(f Fahrenheit) Celsius { return Celsius((f - 32) * 5 / 9) }

func CToK(c Celsius) Kelvin {return Kelvin(c + AbsoluteZeroC)}
func KToC(k Kelvin) Celsius { return Celsius(k) - AbsoluteZeroC}


package main

import (
    "fmt"
    "./tempconv"
)


func main() {
    fmt.Println("AbsoluteZeroK:",tempconv.CToK(tempconv.AbsoluteZeroC))
    fmt.Println("FreezingK:",tempconv.CToK(tempconv.FreezingC))
    fmt.Println("BoilinigK:",tempconv.CToK(tempconv.BoilingC))
}

练习 2.2: 写一个通用的单位转换程序,用类似cf程序的方式从命令行读取参数,如果缺省的话则是从标准输入读取参数,然后做类似Celsius和Fahrenheit的单位转换,长度单位可以对应英尺和米,重量单位可以对应磅和公斤等。

package main

import (
    "fmt"
    "os"
    "bufio"
    "strings"
    "strconv"
    "../ex01/tempconv"
)

type Meter float64
type Feet float64
type Pound float64
type Kilogram float64

func (m Meter) String() string {return fmt.Sprintf("%gm",m)}
func (f Feet) String() string {return fmt.Sprintf("%gft",f)}
func (p Pound) String() string {return fmt.Sprintf("%glb",p)}
func (k Kilogram) String() string {return fmt.Sprintf("%gkg",k)}

func MToF(m Meter) Feet {return Feet(m * 1200 / 3937)}
func FToM(f Feet) Meter {return Meter(f * 3937 / 1200)}
func PToK(p Pound) Kilogram {return Kilogram( p * 0.45359237)}
func KToP(k Kilogram) Pound { return Pound(k / 0.45359237)}


func main() {
    var args []string
    if len(os.Args) > 1 {
        args = os.Args[1:]
    }else{
        r := bufio.NewReader(os.Stdin)
        s, _ := r.ReadString('\n')
        args = []string{strings.TrimSpace(s)}
    }

    for _,arg := range args {
        v, err := strconv.ParseFloat(arg, 64)
        if err != nil {
            fmt.Fprintf(os.Stderr,"unitconv: %v\n",err)
            os.Exit(1)
        }
        {
            f := tempconv.Fahrenheit(v)
            c := tempconv.Celsius(v)
            fmt.Printf("%s = %s,%s = %s\n",f,tempconv.FToC(f),c,tempconv.CToF(c))
        }
        {
            m := Meter(v)
            f := Feet(v)
            fmt.Printf("%s = %s,%s = %s\n",m,MToF(m),f,FToM(f))
        }
        {
            p := Pound(v)
            k := Kilogram(v)
            fmt.Printf("%s = %s, %s = %s\n",p,PToK(p),k,KToP(k))
        }
    }
}


练习 2.3: 重写PopCount函数,用一个循环代替单一的表达式。比较两个版本的性能。(11.4节将展示如何系统地比较两个不同实现的性能。

package popcount

// pc[i] is the population count of i.
var pc [256]byte

func init() {
    for i := range pc {
        pc[i] = pc[i/2] + byte(i&1)
    }
}

// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
    return int(pc[byte(x>>(0*8))] +
        pc[byte(x>>(1*8))] +
        pc[byte(x>>(2*8))] +
        pc[byte(x>>(3*8))] +
        pc[byte(x>>(4*8))] +
        pc[byte(x>>(5*8))] +
        pc[byte(x>>(6*8))] +
        pc[byte(x>>(7*8))])
}

func PopCountByLoop(x uint64) int {
    n := 0
    for i := byte(0); i < 8; i++ {
        n += int(pc[byte(x >>(i*8))])
    }
    return n
}


package popcount

import (
    "testing"
    "reflect"
)

func assert(t *testing.T,expected,actual interface{}){
    if !reflect.DeepEqual(expected,actual){
        t.Errorf("(expected,actual) = (%v,%v)\n",expected,actual)
    }
}

func TestPopCount(t *testing.T) {
    assert(t,32,PopCount(0x1234567890ABCDEF))
}


func TestPopCountByLoop(t *testing.T) {
    assert(t, 32, PopCountByLoop(0x1234567890ABCDEF))
}

func BenchmarkPopCount(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCount(0x1234567890ABCDEF)
    }
}

func BenchmarkPopCountByLoop(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCountByLoop(0x1234567890ABCDEF)
    }
}

练习 2.4: 用移位算法重写PopCount函数,每次测试最右边的1bit,然后统计总数。比较和查表算法的性能差异。

package popcount

// pc[i] is the population count of i.
var pc [256]byte

func init() {
    for i := range pc {
        pc[i] = pc[i/2] + byte(i&1)
    }
}

// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
    return int(pc[byte(x>>(0*8))] +
        pc[byte(x>>(1*8))] +
        pc[byte(x>>(2*8))] +
        pc[byte(x>>(3*8))] +
        pc[byte(x>>(4*8))] +
        pc[byte(x>>(5*8))] +
        pc[byte(x>>(6*8))] +
        pc[byte(x>>(7*8))])
}

func PopCountByBitShift(x uint64) int {
    n := 0
    for i := uint(0); i < 64; i++ {
        if (x>>i)&1 != 0 {
            n++
        }
    }
    return n
}

package popcount

import (
    "reflect"
    "testing"
)

func assert(t *testing.T, expected, actual interface{}) {
    if !reflect.DeepEqual(expected, actual) {
        t.Errorf("(expected, actual) = (%v, %v)\n", expected, actual)
    }
}

func TestPopCount(t *testing.T) {
    assert(t, 32, PopCount(0x1234567890ABCDEF))
}

func TestPopCountByBitShift(t *testing.T) {
    assert(t, 32, PopCountByBitShift(0x1234567890ABCDEF))
}

func BenchmarkPopCount(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCount(0x1234567890ABCDEF)
    }
}

func BenchmarkPopCountByBitShift(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCountByBitShift(0x1234567890ABCDEF)
    }
}


练习 2.5: 表达式x&(x-1)用于将x的最低的一个非零的bit位清零。使用这个算法重写PopCount函数,然后比较性能。

package popcount

// pc[i] is the population count of i.
var pc [256]byte

func init() {
    for i := range pc {
        pc[i] = pc[i/2] + byte(i&1)
    }
}

// PopCount returns the population count (number of set bits) of x.
func PopCount(x uint64) int {
    return int(pc[byte(x>>(0*8))] +
        pc[byte(x>>(1*8))] +
        pc[byte(x>>(2*8))] +
        pc[byte(x>>(3*8))] +
        pc[byte(x>>(4*8))] +
        pc[byte(x>>(5*8))] +
        pc[byte(x>>(6*8))] +
        pc[byte(x>>(7*8))])
}

func PopCountByBitClear(x uint64) int {
    n := 0
    for x != 0 {
        x = x & (x - 1)
        n++
    }
    return n
}

package popcount

import (
    "reflect"
    "testing"
)

func assert(t *testing.T, expected, actual interface{}) {
    if !reflect.DeepEqual(expected, actual) {
        t.Errorf("(expected, actual) = (%v, %v)\n", expected, actual)
    }
}

func TestPopCount(t *testing.T) {
    assert(t, 32, PopCount(0x1234567890ABCDEF))
}

func TestPopCountByBitClear(t *testing.T) {
    assert(t, 32, PopCountByBitClear(0x1234567890ABCDEF))
}

func BenchmarkPopCount(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCount(0x1234567890ABCDEF)
    }
}

func BenchmarkPopCountByBitClear(b *testing.B) {
    for i := 0; i < b.N; i++ {
        PopCountByBitClear(0x1234567890ABCDEF)
    }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容