LoginSignup
1
0

More than 5 years have passed since last update.

A Tour of GoのExerciseの解答

Last updated at Posted at 2017-02-05

Exercise: Loops and Functions

package main

import (
    "fmt"
)

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

func main() {
    fmt.Println(Sqrt(2))
}

Exercise: Slices

package main

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

func Pic(dx, dy int) [][]uint8 {
    // 一旦、2次元配列を0で初期化
    result := make([][]uint8, dy)
    for i := range result {
        result[i] = make([]uint8, dx)
    }

    for y := 0; y < dy; y++ {
        for x := 0; x < dx; x++ {
            //result[x][y] = uint8((x + y) / 2)
            //result[x][y] = uint8(x * y)
            result[x][y] = uint8(x ^ y)
        }
    }

    return result
}

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

Exercise: Maps

package main

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

func WordCount(s string) map[string]int {
    counts := make(map[string]int)
    fields := strings.Fields(s)
    for _, field := range fields {
        counts[field] += 1
    }
    return counts
}

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

Exercise: Fibonacci closure

package main

import "fmt"

// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
    var f0, f1, f2 int = 0, 1, 0
    return func() int {
        fib := f0
        f2 = f0 + f1
        f0 = f1
        f1 = f2
        return fib
    }
}

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0