Last active
December 12, 2018 02:36
-
-
Save chochinlu/95b72895690c587fb9bd7d1f2c0a0256 to your computer and use it in GitHub Desktop.
A tour of Go: Exercises
This file contains 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 := 2.0 | |
s := 0.0 | |
for { | |
z = z - (z*z-x)/(2*z) | |
if math.Abs(s-z) < 1e-15 { | |
break | |
} | |
s = z | |
} | |
return s | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(math.Sqrt(2)) | |
} | |
/******************************************************************************************************/ | |
/** --- 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)) | |
} | |
//Sqrt is sqrt | |
func Sqrt(x float64) (float64, error) { | |
if x < 0 { | |
return 0, ErrNegativeSqrt(x) | |
} | |
z := 2.0 | |
s := 0.0 | |
for { | |
z = z - (z*z-x)/(2*z) | |
if math.Abs(s-z) < 1e-15 { | |
break | |
} | |
s = z | |
} | |
return s, nil | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(Sqrt(-2)) | |
} | |
/******************************************************************************************************/ | |
/** --- Exercise: Readers --- **/ | |
package main | |
import ( | |
"fmt" | |
) | |
type MyReader struct{} | |
func (t MyReader) Read(b []byte) (int, error) { | |
for i := range b { | |
b[i] = 'A' | |
} | |
return len(b), nil | |
} | |
func main() { | |
reader.Validate(MyReader{}) | |
} | |
/******************************************************************************************************/ | |
/** --- Exercise: rot13Reader --- **/ | |
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
func rot13(p byte) byte { | |
switch { | |
case (p >= 'A' && p <= 'M') || (p >= 'a' && p <= 'm'): | |
return p + 13 | |
case (p >= 'N' && p <= 'Z') || (p >= 'n' && p <= 'z'): | |
return p - 13 | |
default: | |
return p | |
} | |
} | |
func (reader rot13Reader) Read(b []byte) (n int, err error) { | |
n, err = reader.r.Read(b) | |
if err != nil { | |
return | |
} | |
for i := 0; i < n; i++ { | |
b[i] = rot13(b[i]) | |
} | |
return | |
} | |
func main() { | |
s := strings.NewReader("Lbh penpxrq gur pbqr!") | |
r := rot13Reader{s} | |
io.Copy(os.Stdout, &r) | |
} | |
/******************************************************************************************************/ | |
/** --- Exercise: Slices --- **/ | |
package main | |
import "golang.org/x/tour/pic" | |
func Pic(dx, dy int) [][]uint8 { | |
pic := make([][]uint8, dy) | |
for i := range pic { | |
pic[i] = make([]uint8, dx) | |
for j := range pic[i] { | |
pic[i][j] = uint8(i*j) | |
} | |
} | |
return pic | |
} | |
func main() { | |
pic.Show(Pic) | |
} | |
/******************************************************************************************************/ | |
/** --- Exercise: Images --- **/ | |
package main | |
import ( | |
"image" | |
"image/color" | |
"golang.org/x/tour/pic" | |
) | |
type Image struct{ | |
width, height int | |
color uint8 | |
} | |
func (img Image) ColorModel() color.Model { | |
return color.RGBAModel | |
} | |
func (img Image) Bounds() image.Rectangle { | |
return image.Rect(0, 0, img.width, img.height) | |
} | |
func (img Image) At(x, y int) color.Color { | |
return color.RGBA{img.color + uint8(x), img.color + uint8(y), 255, 255} | |
} | |
func main() { | |
m := Image{100, 100, 80} | |
pic.ShowImage(m) | |
} | |
/******************************************************************************************************/ | |
/** --- Exercise: Equivalent Binary Trees --- **/ | |
func _walk(t *tree.Tree, ch chan int) { | |
if t != nil { | |
_walk(t.Left, ch) | |
ch <- t.Value | |
_walk(t.Right, ch) | |
} | |
} | |
func Walk(t *tree.Tree, ch chan int) { | |
_walk(t, ch) | |
close(ch) | |
} | |
func Same(t1, t2 *Tree) bool { | |
ch1 := make(chan int) | |
ch2 := make(chan int) | |
go Walk(t1, ch1) | |
go Walk(t2, ch2) | |
for v1 := range ch1 { | |
if v1 != <-ch2 { | |
return false | |
} | |
} | |
return true | |
} | |
func main() { | |
ch := make(chan int) | |
go Walk(New(1), ch) | |
for v := range ch { | |
fmt.Println(v) | |
} | |
} | |
/******************************************************************************************************/ | |
/** --- Exercise: Web Crawler --- **/ | |
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) | |
} | |
// Fetched urls | |
type Fetched struct { | |
urls []string | |
mux sync.Mutex | |
} | |
var catched = Fetched{urls: []string{}} | |
func isFetched(url string) bool { | |
for _, v := range catched.urls { | |
if v == url { | |
return true | |
} | |
} | |
return false | |
} | |
// Crawl uses fetcher to recursively crawl | |
// pages starting with url, to a maximum of depth. | |
func Crawl(url string, depth int, fetcher Fetcher) { | |
// Fetch URLs in parallel. | |
// Don't fetch the same URL twice. | |
// This implementation doesn't do either: | |
if depth <= 0 { | |
return | |
} | |
catched.mux.Lock() | |
if isFetched(url) { | |
catched.mux.Unlock() | |
return | |
} | |
body, urls, err := fetcher.Fetch(url) | |
if err != nil { | |
catched.mux.Unlock() | |
fmt.Println(err) | |
return | |
} | |
catched.urls = append(catched.urls, url) // Add the url to the catched url array when fetching completed. | |
catched.mux.Unlock() | |
fmt.Printf("found: %s %q\n", url, body) | |
ch := make(chan bool) | |
for _, u := range urls { | |
go func(url string) { | |
Crawl(url, depth-1, fetcher) | |
ch <- true | |
}(u) | |
} | |
for range urls { | |
<-ch | |
} | |
return | |
} | |
func main() { | |
Crawl("https://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{ | |
"https://golang.org/": &fakeResult{ | |
"The Go Programming Language", | |
[]string{ | |
"https://golang.org/pkg/", | |
"https://golang.org/cmd/", | |
}, | |
}, | |
"https://golang.org/pkg/": &fakeResult{ | |
"Packages", | |
[]string{ | |
"https://golang.org/", | |
"https://golang.org/cmd/", | |
"https://golang.org/pkg/fmt/", | |
"https://golang.org/pkg/os/", | |
}, | |
}, | |
"https://golang.org/pkg/fmt/": &fakeResult{ | |
"Package fmt", | |
[]string{ | |
"https://golang.org/", | |
"https://golang.org/pkg/", | |
}, | |
}, | |
"https://golang.org/pkg/os/": &fakeResult{ | |
"Package os", | |
[]string{ | |
"https://golang.org/", | |
"https://golang.org/pkg/", | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment