《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)
    }
}

你可能感兴趣的:(《GO语言圣经》读书笔记 第二章 习题解答)