A Tour Of Go : Exercise

## [Exercise: Loops and Functions](https://go-tour-jp.appspot.com/flowcontrol/8)

```go:exercise-loops-and-functions.go
package main

import (
	"fmt"
	"math"
)

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

func Sqrt(x float64) float64 {
	z0, z := 1.0, x
	for math.Abs(z-z0)/z > 1e-10 {
		z0, z = z, z-(z*z-x)/(2*z)
	}
	return z
}

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

```

## [Exercise: Slices](https://go-tour-jp.appspot.com/moretypes/18)
```go:exercise-slices.go
package main

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

func Pic(dx, dy int) [][]uint8 {
	pic := make([][]uint8, dy)
	for y := range pic {
		pic[y] = make([]uint8, dx)
		for x := range pic[y] {
			pic[y][x] = uint8((x + y) / 2)
		}
	}
	return pic
}

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

## [Exercise: Maps](https://go-tour-jp.appspot.com/moretypes/23)
```go:exercise-maps.go
package main

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

func WordCount(s string) map[string]int {
	words := make(map[string]int)
	for _, f := range strings.Fields(s) {
		words[f]++
	}

	return words
}

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

## [Exercise: Fibonacci closure](https://go-tour-jp.appspot.com/moretypes/26)
```go:exercise-fibonacci-closure.go
package main

import "fmt"

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

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

## [Exercise: Stringers](https://go-tour-jp.appspot.com/methods/18)
```go:exercise-stringers.go
package main

import "fmt"

type IPAddr [4]byte

// TODO: Add a "String() string" method to IPAddr.
func (addr IPAddr) String() (s string) {
	for _, v := range addr {
		s += fmt.Sprintf("%d.", v)
	}
	return s[:len(s)-1]
}

func main() {
	hosts := map[string]IPAddr{
		"loopback":  {127, 0, 0, 1},
		"googleDNS": {8, 8, 8, 8},
	}
	for name, ip := range hosts {
		fmt.Printf("%v: %v\n", name, ip)
	}
}
```

## [Exercise: Errors](https://go-tour-jp.appspot.com/methods/20)
```go:exercise-errors.go
package main

import (
	"fmt"
	"math"
)

type ErrNegativeSqrt float64

func (e ErrNegativeSqrt) Error() string {
	return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}

func Sqrt(x float64) (float64, error) {
	if x < 0 {
		return 0, ErrNegativeSqrt(x)
	}
	
	z0, z := 1.0, x
	for math.Abs(z-z0)/z > 1e-10 {
		z0, z = z, z-(z*z-x)/(2*z)
	}
	return z, nil
}

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

## [Exercise: Readers](https://go-tour-jp.appspot.com/methods/22)
```go:exercise-readers.go
package main

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

type MyReader struct{}

// TODO: Add a Read([]byte) (int, error) method to MyReader.
func (a MyReader) Read(rb []byte) (n int, e error) {
	for i, _ := range rb {
		rb[i] = 'A'
		n++
	}
	return
}

func main() {
	reader.Validate(MyReader{})
}
```

## [Exercise: rot13Reader](https://go-tour-jp.appspot.com/methods/23)
```go:exercise-rot13reader.go
package main

import (
	"io"
	"os"
	"strings"
)

type rot13Reader struct {
	r io.Reader
}

func (a *rot13Reader) Read(rb []byte) (n int, e error) {
	n, e = a.r.Read(rb)
	if e == nil {
		for i, v := range rb {
			switch {
			case v >= 'A' && v <= 'Z':
				rb[i] = (v-'A'+13)%26 + 'A'
			case v >= 'a' && v <= 'z':
				rb[i] = (v-'a'+13)%26 + 'a'
			}
		}
	}

	return
}

func main() {
	s := strings.NewReader("Lbh penpxrq gur pbqr!")
	r := rot13Reader{s}
	io.Copy(os.Stdout, &r)

	s2 := strings.NewReader("You cracked the code!")
	r2 := rot13Reader{s2}
	io.Copy(os.Stdout, &r2)
}
```
## [Exercise: Images](https://go-tour-jp.appspot.com/methods/25)
```go:exercise-images.go
package main

import (
	"golang.org/x/tour/pic"
	"image"
	"image/color"
)

type Image struct{}

func (im Image) ColorModel() color.Model {
	return color.RGBAModel
}

func (im Image) Bounds() image.Rectangle {
	return image.Rect(0, 0, 255, 255)
}

func (im Image) At(x, y int) color.Color {
	v := uint8(x * y)
	return color.RGBA{v, v, 255, 255}
}

func main() {
	m := Image{}
	pic.ShowImage(m)
}
```

## [Exercise: Equivalent Binary Trees](https://go-tour-jp.appspot.com/concurrency/8)
```go:exercise-equivalent-binary-trees.go
package main

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

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
	var walker func(t *tree.Tree)
	walker = func(t *tree.Tree) {
		if t == nil {
			return
		}
		walker(t.Left)
		ch <- t.Value
		walker(t.Right)
	}
	walker(t)
	close(ch)
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
	ch1, ch2 := make(chan int), make(chan int)

	go Walk(t1, ch1)
	go Walk(t2, ch2)

	for {
		v1, ok1 := <-ch1
		v2, ok2 := <-ch2

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

		if !ok1 {
			break
		}
	}

	return true
}

func main() {
	ch := make(chan int)
	go Walk(tree.New(1), ch)
	for v := range ch {
		println("tree:", v)
	}

	println(Same(tree.New(1), tree.New(1)))
	println(Same(tree.New(1), tree.New(2)))
}

```
## [Exercise: Web Crawler](https://go-tour-jp.appspot.com/concurrency/10)

こちらのページを参考にさせていただきました！
https://qiita.com/Blufe/items/1f7efbedf015a5c2ba9b#exercise-web-crawler

```go:exercise-web-crawler.go
package main

import (
	"fmt"
	"sync"
)

type Fetcher interface {
	// Fetch returns the body of URL and
	// a slice of URLs found on that page.
	Fetch(url string) (body string, urls []string, err error)
}

// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
	wait := &sync.WaitGroup{}

	var mux sync.Mutex
	cache := map[string]int{}

	var isCrawled func(string) bool
	isCrawled = func(url string) bool {
		mux.Lock()
		cache[url]++
		mux.Unlock()

		return cache[url] > 1
	}

	var crawler func(string, int)
	crawler = func(url string, depth int) {
		defer wait.Done()
		// Too deep
		if depth <= 0 {
			return
		}

		// Don't fetch the same URL twice
		if isCrawled(url) {
			return
		}

		body, urls, err := fetcher.Fetch(url)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Printf("found: %s %q\n", url, body)

		// Fetch URLs in parallel.
		for _, u := range urls {
			wait.Add(1)
			go crawler(u, depth-1)
		}

	}

	wait.Add(1)
	go crawler(url, depth)

	wait.Wait()
}

func main() {
	Crawl("http://golang.org/", 4, fetcher)
}

// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult

type fakeResult struct {
	body string
	urls []string
}

func (f fakeFetcher) Fetch(url string) (string, []string, error) {
	if res, ok := f[url]; ok {
		return res.body, res.urls, nil
	}
	return "", nil, fmt.Errorf("not found: %s", url)
}

// fetcher is a populated fakeFetcher.
var fetcher = fakeFetcher{
	"http://golang.org/": &fakeResult{
		"The Go Programming Language",
		[]string{
			"http://golang.org/pkg/",
			"http://golang.org/cmd/",
		},
	},
	"http://golang.org/pkg/": &fakeResult{
		"Packages",
		[]string{
			"http://golang.org/",
			"http://golang.org/cmd/",
			"http://golang.org/pkg/fmt/",
			"http://golang.org/pkg/os/",
		},
	},
	"http://golang.org/pkg/fmt/": &fakeResult{
		"Package fmt",
		[]string{
			"http://golang.org/",
			"http://golang.org/pkg/",
		},
	},
	"http://golang.org/pkg/os/": &fakeResult{
		"Package os",
		[]string{
			"http://golang.org/",
			"http://golang.org/pkg/",
		},
	},
}

```