何かやってみるブログ

興味をもったことに関して書いています。技術系の記事が多いです。

A Tour of Go(Basics)のExerciseを解いてみた

今回はA Tour of GoのBasicsの章のExerciseを解いてみたので、メモ代わりに残します。

Exercise: Loops and Functions

https://go-tour-jp.appspot.com/flowcontrol/8

package main

import (
    "fmt"
)

func Sqrt(x float64) float64 {
    z := 1.0
    for i := 0; i < 10; i++ {
        z -= (z*z - x) / (2 * z)
    }
    return z
}

func main() {
    fmt.Println(Sqrt(2))
}
 
// => 1.414213562373095

Exercise: Slices

https://go-tour-jp.appspot.com/moretypes/18

package main

import "golang.org/x/tour/pic"

func Pic(dx, dy int) [][]uint8 {
    sli := make([][]uint8, dy)
    for index, v := range sli {
        for i := 0; i < dx; i++ {
            value := index * i
            v = append(v, uint8(value))
        }
        sli = append(sli, v)
    }
    return sli[dy:]
}

func main() {
    pic.Show(Pic)
}

Exercise: Maps

https://go-tour-jp.appspot.com/moretypes/23

package main

import (
    "fmt"
    "strings"
    "golang.org/x/tour/wc"
)

func WordCount(s string) map[string]int {
    words := strings.Fields(s)
    fmt.Println(words)
    result := map[string]int{}
    for _, v := range words {
        if result[v] >= 1 {
            result[v] = result[v] + 1
        } else {
            result[v] = 1
        }
    }
    return result
}

func main() {
    wc.Test(WordCount)
}

Exercise: Fibonacci closure

https://go-tour-jp.appspot.com/moretypes/26

package main

import (
    "fmt"
)

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    var a, b int = 1, 0
    return func() int {
        a, b = b, a+b
        return a
    }
}

func main() {
    f := fibonacci()
    for i := 0; i < 10; i++ {
        fmt.Println(f())
    }
}