As I am going through the Tour of Go I found there are some exercise that require some problem solving. I’d like to share my solutions that I’ve come up with for these. I’ll be updating these as I complete the tour of go!

Exercise: Loops and Functions

package main

import (
	"fmt"
	"math"
)

func Sqrt(x float64) float64 {
	z := 1.0
	prevZ := z
	diff := 0.00000001
	for {
		z -= (z*z - x) / (2*z)
		if diff > math.Abs(z - prevZ) {
			break
		}
		prevZ = z
	}
	return z
}

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

Exercise: Slices

package main

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

func Pic(dx, dy int) [][]uint8 {
	result := make([][]uint8, dy)
	for i := range result {
		inner := make([]uint8, dx)
		for j := range inner {
			inner[j] = uint8(i)
		}

		result[i] = inner
	}

	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 {
	wordCount := make(map[string]int)

	words := strings.Fields(s)

	for _, word := range words {
		wordCount[word] += 1
	}

	return wordCount
}

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

Exercise: Stringers

package main

import "fmt"

type IPAddr [4]byte

func (ip IPAddr) String() string {
	return fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3])
}

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

package main

import (
	"fmt"
	"math"
)

type ErrNegativeSqrt float64

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


func Sqrt(x float64) (float64, error) {
    if x < 0 {
        return 0, ErrNegativeSqrt(x)
    }
	
	z := 1.0
	prevZ := z
	diff := 0.00000001
	for {
		z -= (z*z - x) / (2*z)
		if diff > math.Abs(z - prevZ) {
			break
		}
		prevZ = z
	}
	return z, nil
}

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

Exercise: Readers

package main

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

type MyReader struct{}

func (r MyReader) Read(b []byte) (int, error) {
	b[0] = 65
	return 1, nil	
}

// TODO: Add a Read([]byte) (int, error) method to MyReader.

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