Skip to content

Instantly share code, notes, and snippets.

@wuxiao356
Last active January 9, 2017 03:57
Show Gist options
  • Save wuxiao356/264cd0f3b37773a2668a to your computer and use it in GitHub Desktop.
Save wuxiao356/264cd0f3b37773a2668a to your computer and use it in GitHub Desktop.
A Tour of Go: Exercises Solution
//Exercise: Loops and Functions
package main
import (
"fmt"
"math"
)
const delta = 0.000000000001
func Sqrt(x float64) (value float64, iteration int) {
z := 1.0
i := 0
for math.Abs(z*z -x) > delta{
z = z - (z*z - x)/(z*2)
i++
}
return z,i
}
func main() {
fmt.Printf("math.Sqrt(2) is %v\n", math.Sqrt(2))
value, iteration := Sqrt(2)
fmt.Printf("My Sqrt(2) is %v and it takes %v iterations", value, iteration)
}
//Exercise: Slices
package main
import "code.google.com/p/go-tour/pic"
func Pic(dx, dy int) [][]uint8 {
image := make([][]uint8, dy)
for i := range image {
image[i] = make([]uint8, dx)
for j := range image[i] {
image[i][j] = uint8(i*i + j*j)
}
}
return image
}
func main() {
pic.Show(Pic)
}
//Exercise: Maps
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
chuncks := strings.Fields(s)
result := make(map[string]int)
for i:= 0; i < len(chuncks); i++{
if _, exist := result[chuncks[i]]; !exist{
result[chuncks[i]] = 1
}else{
result[chuncks[i]]++
}
}
return result
}
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 {
num1, num2, sum := 0, 1, 0
return func() int{
sum = num1 + num2
num1 = num2
num2 = sum
return num1
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
//Exercise: Stringers
package main
import "fmt"
type IPAddr [4]byte
// TODO: Add a "String() string" method to IPAddr.
func (a IPAddr)String() string{
return fmt.Sprintf("%v.%v.%v.%v",a[0],a[1],a[2],a[3])
}
func main() {
addrs := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for n, a := range addrs {
fmt.Printf("%v: %v\n", n, a)
}
}
//Exercise: Errors
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (err ErrNegativeSqrt)Error() string{
return fmt.Sprintf("\"cannot Sqrt negative number: %F\"", err)
}
func Sqrt(x float64) (float64, error) {
z := 1.0
if x >= 0 {
for math.Abs(z*z - x) > 0.000000000001{
z = z - (z*z - x)/(z*2)
}
return z, nil
}else{
return x, ErrNegativeSqrt(x)
}
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
//Exercise: Readers
package main
import "code.google.com/p/go-tour/reader"
type MyReader struct{}
// TODO: Add a Read([]byte) (int, error) method to MyReader.
func (r MyReader)Read(b []byte) (int, error) {
for i := range b {
b[i] = 'A'
}
return len(b),nil
}
func main() {
reader.Validate(MyReader{})
}
//Exercise: rot13Reader
import (
"io"
"os"
"strings"
"unicode"
)
type rot13Reader struct {
r io.Reader
}
func (rot13 rot13Reader)Read(b []byte) (int, error) {
length, err := rot13.r.Read(b)
for i := range b {
if unicode.IsLetter(rune(b[i])) {
if unicode.IsUpper(rune(b[i])) {
b[i] = (b[i] - 'A' + 13) %26 + 'A'
}else{
b[i] = (b[i] - 'a' + 13) %26 + 'a'
}
}
}
return length, err
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
//Exercise: HTTP Handlers
package main
import (
"fmt"
"log"
"net/http"
)
type String string
type Struct struct {
Greeting string
Punct string
Who string
}
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s)
}
func (s Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s.Greeting, s.Punct, s.Who)
}
func main() {
http.Handle("/string", String("I'm a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
log.Fatal(http.ListenAndServe("localhost:5000", nil))
}
//Exercise: Images
package main
import (
"code.google.com/p/go-tour/pic"
"image"
"image/color"
)
type Image struct{}
func (img Image)ColorModel() color.Model {
return color.RGBAModel
}
func (img Image)Bounds() image.Rectangle {
return image.Rect(0, 0, 512, 512)
}
func (img Image)At(x,y int) color.Color {
return color.RGBA{uint8(float64(x*x+y*y)*0.5),uint8(float64(x*x+y*y)*0.5),255,255}
}
func main() {
m := Image{}
pic.ShowImage(m)
}
//Exercise: Equivalent Binary Trees
package main
import (
"code.google.com/p/go-tour/tree"
"fmt"
)
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int){
if t == nil { return }
Walk(t.Left, ch)
ch <- t.Value
Walk(t.Right, ch)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
ch1 := make(chan int)
ch2 := make(chan int)
go Walk(t1,ch1)
go Walk(t2, ch2)
for i := 0; i < 10; i++ {
x, y := <-ch1, <-ch2
if x != y {return false}
}
return true
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment