Last active
January 5, 2020 04:12
-
-
Save dudo/824799dde85d9cc62db0a3504f6bab30 to your computer and use it in GitHub Desktop.
Go Exercises
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
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) { | |
defer close(ch) // <- closes the channel when this function returns | |
var walk func(t *tree.Tree) | |
walk = func(t *tree.Tree) { | |
if t == nil { | |
return | |
} | |
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, 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 i := range ch { | |
fmt.Println(i) | |
} | |
fmt.Println("Should return true:", Same(tree.New(1), tree.New(1))) | |
fmt.Println("Should return false:", Same(tree.New(1), tree.New(2))) | |
} |
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
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.0, ErrNegativeSqrt(x) | |
} | |
z := x / 2 | |
for prev := 0.0; math.Abs(prev-z) > 1e-8; { | |
prev = z | |
z -= (z*z - x) / (2 * z) | |
} | |
return z, nil | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
fmt.Println(Sqrt(-2)) | |
} |
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
package main | |
import "fmt" | |
func fibonacci() func() int { | |
a, b := 0, 1 | |
return func() int { | |
defer func() { a, b = b, a+b }() | |
return a | |
} | |
} | |
func main() { | |
f := fibonacci() | |
for i := 0; i < 10; i++ { | |
fmt.Println(f()) | |
} | |
} |
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
package main | |
import ( | |
"image" | |
"image/color" | |
"golang.org/x/tour/pic" | |
) | |
type Image struct{ | |
w int | |
h int | |
} | |
func (i Image) Bounds() image.Rectangle { | |
return image.Rect(0, 0, i.w, i.h) | |
} | |
func (i Image) ColorModel() color.Model { | |
return color.RGBAModel | |
} | |
func (i Image) At(x, y int) color.Color { | |
r, g, b := uint8(x+y), uint8(x^y), uint8((x+y)/2) | |
return color.RGBA{r, g, b, 255} | |
} | |
func main() { | |
m := Image{100, 100} | |
pic.ShowImage(m) | |
} |
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
package main | |
import ( | |
"fmt" | |
"math" | |
) | |
func Sqrt(x float64) float64 { | |
z := x / 2 | |
for prev := 0.0; math.Abs(prev-z) > 1e-8; { | |
prev = z | |
z -= (z*z - x) / (2 * z) | |
} | |
return z | |
} | |
func main() { | |
fmt.Println(Sqrt(2)) | |
} |
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
package main | |
import ( | |
"golang.org/x/tour/wc" | |
"strings" | |
) | |
func WordCount(s string) map[string]int { | |
m := make(map[string]int) | |
fields := strings.Fields(s) | |
for _, v := range fields { | |
m[v]++ | |
} | |
return m | |
} | |
func main() { | |
wc.Test(WordCount) | |
} |
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
package main | |
import "golang.org/x/tour/reader" | |
type MyReader struct{} | |
func (r MyReader) Read(b []byte) (int, error) { | |
b[0] = 'A' | |
return 1, nil | |
} | |
func main() { | |
reader.Validate(MyReader{}) | |
} |
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
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
type rot13Reader struct { | |
r io.Reader | |
} | |
func rot13(b byte) byte { | |
var beg byte | |
if b >= 'A' && b <= 'Z' { | |
beg = 'A' | |
} else if b >= 'a' && b <= 'z' { | |
beg = 'a' | |
} else { | |
return b | |
} | |
return (((b - beg) + 13) % 26) + beg | |
} | |
func (r rot13Reader) Read(b []byte) (int, error) { | |
size, err := r.r.Read(b) | |
for i, v := range b { | |
b[i] = rot13(v) | |
} | |
return size, err | |
} | |
func main() { | |
s := strings.NewReader("Lbh penpxrq gur pbqr!") | |
r := rot13Reader{s} | |
io.Copy(os.Stdout, &r) | |
} |
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
package main | |
import "golang.org/x/tour/pic" | |
func Pic(dx, dy int) [][]uint8 { | |
r := make([][]uint8, dy) | |
for i := range r { | |
r[i] = make([]uint8, dx) | |
for j := range r[i] { | |
r[i][j] = image(i, j) | |
} | |
} | |
return r | |
} | |
func image(x, y int) uint8 { | |
return uint8((y-x)^x-y) | |
} | |
func main() { | |
pic.Show(Pic) | |
} |
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
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) | |
} | |
} |
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
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) | |
} | |
type SafeCounter struct { | |
v map[string]bool | |
mux sync.Mutex | |
wg sync.WaitGroup | |
} | |
var c SafeCounter = SafeCounter{v: make(map[string]bool)} | |
func (s SafeCounter) checkvisited(url string) bool { | |
s.mux.Lock() | |
defer s.mux.Unlock() | |
_, ok := s.v[url] | |
if ok == false { | |
s.v[url] = true | |
return false | |
} | |
return true | |
} | |
// Crawl uses fetcher to recursively crawl | |
// pages starting with url, to a maximum of depth. | |
func Crawl(url string, depth int, fetcher Fetcher) { | |
defer c.wg.Done() | |
if depth <= 0 { | |
return | |
} | |
if c.checkvisited(url) { | |
return | |
} | |
body, urls, err := fetcher.Fetch(url) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("found: %s %q\n", url, body) | |
for _, u := range urls { | |
c.wg.Add(1) | |
go Crawl(u, depth-1, fetcher) | |
} | |
return | |
} | |
func main() { | |
c.wg.Add(1) | |
Crawl("http://golang.org/", 4, fetcher) | |
c.wg.Wait() | |
} | |
// 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/", | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment