Last active
November 20, 2015 14:00
-
-
Save fonglh/d5e556ad14cf36f7c6a5 to your computer and use it in GitHub Desktop.
Gotour solutions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Exercise: Loops and Functions | |
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func Sqrt(x float64) float64 { | |
z := float64(1) | |
old_z := float64(1) | |
delta := 10.0 | |
for math.Abs(delta) > 0.0000005 { | |
old_z = z | |
z = z - (z*z - x)/(2*z) | |
delta = z - old_z | |
} | |
return z | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(math.Sqrt(2)) | |
} | |
// Exercise: Slices | |
package main | |
import "golang.org/x/tour/pic" | |
func Pic(dx, dy int) [][]uint8 { | |
myPic := make([][]uint8, dy) | |
//allocate | |
for i := range myPic { | |
myPic[i] = make([]uint8, dx) | |
} | |
for x := 0; x < dx; x++ { | |
for y := 0; y < dy; y++ { | |
myPic[x][y] = uint8((x+y)/2) | |
} | |
} | |
return myPic | |
} | |
func main() { | |
pic.Show(Pic) | |
} | |
// Exercise: Maps | |
package main | |
import ( | |
"golang.org/x/tour/wc" | |
"strings" | |
) | |
func WordCount(s string) map[string]int { | |
wordList := strings.Fields(s) | |
counts := make(map[string]int) | |
for _, word := range wordList { | |
_, ok := counts[word] | |
if ok { | |
counts[word] += 1 | |
} else { | |
counts[word] = 1 | |
} | |
} | |
return counts | |
} | |
func main() { | |
wc.Test(WordCount) | |
} | |
// Exercise: Fibonacci Closures | |
package main | |
import "fmt" | |
// fibonacci is a function that returns | |
// a function that returns an int. | |
func fibonacci() func() int { | |
prev, curr := 0, 1 | |
return func() int { | |
next := prev + curr | |
prev = curr | |
curr = next | |
return prev | |
} | |
} | |
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 (ip IPAddr) String() string { | |
return fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[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 (e ErrNegativeSqrt) Error() string { | |
return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e)) | |
} | |
func Sqrt(x float64) (float64, error) { | |
if x < 0 { | |
return 0, ErrNegativeSqrt(x) | |
} else { | |
z := float64(1) | |
old_z := float64(1) | |
delta := 10.0 | |
for math.Abs(delta) > 0.0000005 { | |
old_z = z | |
z = z - (z*z - x)/(2*z) | |
delta = z - old_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{} | |
// TODO: Add a Read([]byte) (int, error) method to MyReader. | |
func (MyReader) Read(b []byte) (int, error) { | |
length := len(b) | |
for i := range b { | |
b[i] = 'A' | |
} | |
return length, nil | |
} | |
func main() { | |
reader.Validate(MyReader{}) | |
} | |
// Exercise: ROT13 Reader | |
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
func (rot *rot13Reader) Read(b []byte) (n int, err error) { | |
n, err = rot.r.Read(b) | |
for i, letter := range b { | |
if (letter >= 'A' || letter >= 'a') && (letter < 'N' || letter < 'n') { | |
b[i] = letter + 13 | |
} else if (letter >= 'N' || letter >= 'n') && (letter <= 'Z' || letter <= 'z') { | |
b[i] = letter - 13 | |
} | |
} | |
return | |
} | |
func main() { | |
s := strings.NewReader("Lbh penpxrq gur pbqr!") | |
r := rot13Reader{s} | |
io.Copy(os.Stdout, &r) | |
} | |
// Exercise: HTTP Handlers | |
package main | |
import ( | |
"log" | |
"net/http" | |
"fmt" | |
) | |
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.Fprintf(w, "%v %v %v\n", s.Greeting, s.Punct, s.Who) | |
} | |
func main() { | |
// your http.Handle calls here | |
http.Handle("/string", String("I'm a frayed knot.")) | |
http.Handle("/struct", &Struct{"Hello", ";", "Gophers!"}) | |
log.Fatal(http.ListenAndServe("localhost:4001", nil)) | |
} | |
// Exercise: Images | |
package main | |
import ( | |
"golang.org/x/tour/pic" | |
"image" | |
"image/color" | |
) | |
type Image struct{} | |
func (img Image) ColorModel() color.Model { | |
return color.RGBAModel | |
} | |
func (img Image) At(x, y int) color.Color { | |
return color.RGBA{uint8(x)*2, uint8(y)*2, 255, 255} | |
} | |
func (img Image) Bounds() image.Rectangle { | |
return image.Rect(0, 0, 125, 100) | |
} | |
func main() { | |
m := Image{} | |
pic.ShowImage(m) | |
} | |
// Exercise: Equivalent Binary Trees | |
package main | |
import ( | |
"fmt" | |
"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) { | |
if t != nil { | |
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++ { | |
if <-ch1 != <-ch2 { | |
return false | |
} | |
} | |
return true | |
} | |
func main() { | |
/*ch := make(chan int) | |
go Walk(tree.New(2), ch) | |
for i := 0; i < 10; i++ { | |
fmt.Println(<-ch) | |
}*/ | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
} | |
// Exercise: Equivalent Binary Trees | |
// This version doesn't depend on knowing the size of the tree beforehand | |
// Uses defer and closures. Taken from | |
// http://stackoverflow.com/questions/12224042/go-tour-exercise-equivalent-binary-trees/17896390#17896390 | |
package main | |
import ( | |
"fmt" | |
"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) { | |
defer close(ch) | |
var walk func(t *tree.Tree) | |
walk = func(t *tree.Tree) { | |
if t != nil { | |
walk(t.Left) | |
ch <- t.Value | |
walk(t.Right) | |
} | |
} | |
walk(t) | |
} | |
// 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 { | |
n1, ok1 := <-ch1 | |
n2, ok2 := <-ch2 | |
if n1 != n2 || ok1 != ok2 { | |
return false | |
} | |
if !ok1 { | |
break | |
} | |
} | |
return true | |
} | |
func main() { | |
/*ch := make(chan int) | |
go Walk(tree.New(2), ch) | |
for i := 0; i < 10; i++ { | |
fmt.Println(<-ch) | |
}*/ | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment