Skip to content

Instantly share code, notes, and snippets.

@fmassicano
Last active February 1, 2019 22:52
Show Gist options
  • Save fmassicano/ab24032236c6b42f98214dae37a49f88 to your computer and use it in GitHub Desktop.
Save fmassicano/ab24032236c6b42f98214dae37a49f88 to your computer and use it in GitHub Desktop.
A Tour of Go [Answers]
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 struct use sync.Mutex now is safe to use concurrently.
// Map record store the url that was fetched
// Map was choosen because is the faster way to check the urls fetched
type Fetched struct {
record map[string]bool
sync.Mutex
}
var fetched = &Fetched{record:make(map[string]bool)}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
if depth <= 0 {
return
}
///// Steps to guarantee that the url will be unique /////////
// LOCK fetched struct to check if that url is already fetched
fetched.Lock()
if fetched.record[url] {
// UNLOCK fetched struct because the url was already fetched
fetched.Unlock()
return // STOP Crawl
}
fetched.record[url] = true
// UNLOCK fetched struct
fetched.Unlock()
///////////////////////////////////////////////////////////////
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return // STOP Crawl
}
fmt.Printf("found: %s %q\n", url, body)
// By default sends and receives block until both the sender and receiver are ready
// channel to get answers from goroutines
done := make(chan bool)
for _, u := range urls {
go func(url string) {
Crawl(url, depth-1, fetcher)
done <- true // sender
}(u)
<-done // receiver
}
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/",
},
},
}
package main
import (
"golang.org/x/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)
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 {
c1 := make(chan int)
c2 := make(chan int)
go Walk(t1, c1)
go Walk(t2, c2)
for {
v1, ok1 := <- c1
v2, ok2 := <- c2
// fmt.Println(ok1, ok2,v1,v2)
if ok1 != ok2 || v1 != v2 {
return false
}
if !ok1 && !ok2 {
break
}
}
return true
}
func main() {
fmt.Println(Same(tree.New(1),tree.New(1)))
fmt.Println(Same(tree.New(1),tree.New(2)))
}
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
// ErrNegativeSqrt is a error because implement Error()
func (e ErrNegativeSqrt) Error() string {
return "cannot apply Sqrt to negative number: " + fmt.Sprint(float64(e))
}
func Sqrt(x float64) (float64, error) {
// If x < 0 return a error
if x < 0 {return 0,ErrNegativeSqrt(x)}
var diff, z_ant, z float64 = 1, 1.0, 1.0
for diff > 1e-10 {
z_ant = z
z -= (z*z - x) / (2*z)
diff = math.Abs(z - z_ant)
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
package main
import (
"golang.org/x/tour/pic"
"image"
"image/color"
)
type Image struct{
w int
h int
f func(x, y int) uint8
}
func (i Image) ColorModel() (color.Model) {
return color.RGBAModel
}
func (i Image) Bounds() (image.Rectangle) {
return image.Rect(0, 0, i.w, i.h)
}
func (i Image) At(x, y int) (color.Color) {
v := i.f(x, y)
return color.RGBA{v, v, 255, 255}
}
func main() {
//m1 := Image{256,256,func(x, y int) uint8 {return uint8(x^y)}}
//m2 := Image{256,256,func(x, y int) uint8 {return uint8((x+y) / 2)}}
m3 := Image{256,256,func(x, y int) uint8 {return uint8(x*y)}}
pic.ShowImage(m3)
}
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func rot13byte(sb byte) byte {
s := rune(sb)
if s >= 'a' && s <= 'm' || s >= 'A' && s <= 'M' {
sb += 13
} else if s >= 'n' && s <= 'z' || s >= 'N' && s <= 'Z' {
sb -= 13
}
return sb
}
// rot13Reader wraps another io.Reader
func (rot13 rot13Reader) Read(data []byte) (readed int, err error) {
readed, err = rot13.r.Read(data) // r.Read is the wrapped io.Reader [Get the array of bytes]
// Apply the transformation in each byte by rot13byte
for i := 0; i < readed; i++ {
data[i] = rot13byte(data[i])
}
return
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
package main
import (
"golang.org/x/tour/pic"
"math"
)
func a(x, y int) uint8 {
return uint8(y - int(16* math.Sin(float64(x*2))) - 130)
}
func b(x, y int) uint8 {
return uint8(y * y)
}
func c(x , y int) uint8 {
return uint8(x ^ y | x*y&1000000)
}
func makePic(f func(x, y int) uint8) func(dx int, dy int) [][]uint8 {
// function that returns a grid of pixel values
pic := func(dx int, dy int) [][]uint8 {
// two-dimensional array of pixel values
p := make([][]uint8, dy)
for y := range p {
// one-dimensional array of pixel values
p[y] = make([]uint8, dx)
for x := range p[y] {
// pixel value defined by f()
p[y][x] = f(x, y)
}
}
return p
}
return pic
}
func main() {
pic.Show(makePic(a))
//pic.Show(makePic(b))
//pic.Show(makePic(c))
}
package main
import "fmt"
type IPAddr [4]byte
// TODO: Add a "String() string" method to IPAddr.
func (ip IPAddr) String() string {
return fmt.Sprintf("%v.%v.%v.%v",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)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment