Skip to content

Instantly share code, notes, and snippets.

@larryprice
Last active September 11, 2017 18:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larryprice/7647808 to your computer and use it in GitHub Desktop.
Save larryprice/7647808 to your computer and use it in GitHub Desktop.
golang tour exercise solutions
// http://tour.golang.org/
/*
Slide 24: Loops and Functions
*/
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z, zo := x, x
d := float64(1)
for n := 0; n < 10 && !(d < .000000000000001 && d > -.000000000000001); n++ {
zo = z
z = z - (z*z - x) / (2*z)
d = z-zo
}
return z
}
func main() {
n := float64(6)
fmt.Println(Sqrt(n))
fmt.Println(math.Sqrt(n))
}
/*
Slide 36: Slices
*/
package main
import "code.google.com/p/go-tour/pic"
func Pic(dx, dy int) [][]uint8 {
v := make([][]uint8, dy)
for i := range(v) {
v[i] = make([]uint8, dx)
for j := range(v[i]) {
v[i][j] = uint8(i^j)
}
}
return v
}
func main() {
pic.Show(Pic)
}
/*
Slide 41: Maps
*/
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
words := make(map[string]int)
for _, word := range(strings.Fields(s)) {
words[word] += 1
}
return words
}
func main() {
wc.Test(WordCount)
}
/*
Slide 44: Fibonacci closure
*/
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
fib := 0
fibN := 0
return func() int {
if fib == 0 && fibN == 0 {
fib = 1
fibN = 0
} else if fib == 1 && fibN == 0 {
fib = 1
fibN = 1
} else {
pFib := fib
fib += fibN
fibN = pFib
}
return fib
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
/*
Slide 48: Complex cube roots
*/
package main
import "fmt"
func Cbrt(x complex128) complex128 {
z := x
for i := 0; i < 15; i++ {
z = z - (z*z*z-x)/(3*z*z)
}
return z
}
func main() {
fmt.Println(Cbrt(8))
fmt.Println(Cbrt(8i))
fmt.Println(Cbrt(2))
fmt.Println(Cbrt(2i))
}
/*
Slide 56: Errors
*/
package main
import (
"fmt"
)
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)
}
z, zo := x, x
d := float64(1)
for n := 0; n < 10 && !(d < .000000000000001 && d > -.000000000000001); n++ {
zo = z
z = z - (z*z - x) / (2*z)
d = z-zo
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
/*
Slide 58: HTTP Handlers
*/
package main
import (
"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.Fprint(w, 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!"})
http.ListenAndServe("localhost:4000", nil)
}
/*
Slide 60: Images
*/
package main
import (
"code.google.com/p/go-tour/pic"
"image"
"image/color"
)
type Image struct{}
func (i Image) ColorModel() color.Model {
return color.RGBAModel
}
func (i Image) Bounds() image.Rectangle {
return image.Rect(0, 0, 100, 100)
}
func (i Image) At(x, y int) color.Color {
v := uint8(x*y)
return color.RGBA{v, v, 255, 255}
}
func main() {
m := Image{}
pic.ShowImage(m)
}
/*
Slide 61: Rot13 Reader
*/
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (rot13 rot13Reader) Read(p []byte) (int, error) {
n, err := rot13.r.Read(p)
for n = 0; n < len(p); n++ {
if p[n] < 'Z' && p[n] > 'A' {
if p[n] < 'N' {
p[n] = p[n] + 13
} else {
p[n] = p[n] - 13
}
} else if p[n] > 'a' && p[n] < 'z' {
if p[n] < 'n' {
p[n] = p[n] + 13
} else {
p[n] = p[n] - 13
}
}
}
return n, err
}
func main() {
s := strings.NewReader(
"Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
/*
Slide 70: Equivalent Binary Trees
*/
package main
import "code.google.com/p/go-tour/tree"
import "fmt"
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
WalkInternal(t, ch, true)
}
func WalkInternal(t *tree.Tree, ch chan int, closeChannel bool) {
if t.Left != nil {
WalkInternal(t.Left, ch, false)
}
ch <- t.Value
if t.Right != nil {
WalkInternal(t.Right, ch, false)
}
if closeChannel {
close(ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
c1 := make(chan int)
go Walk(t1, c1)
c2 := make(chan int)
go Walk(t2, c2)
for {
x, xOk := <- c1
y, yOk := <- c2
if (xOk != yOk) || (x != y) {
return false
} else if xOk && yOk {
return true
}
}
return false // should never be hit
}
func main() {
fmt.Println("Expected: tree.New(1) == tree.New(1)")
if Same(tree.New(1), tree.New(1)) {
fmt.Println("Actual: tree.New(1) == tree.New(1)")
} else {
fmt.Println("Actual: tree.New(1) != tree.New(1)")
}
fmt.Println()
fmt.Println("Expected: tree.New(1) != tree.New(2)")
if Same(tree.New(1), tree.New(2)) {
fmt.Println("Actual: tree.New(1) == tree.New(2)")
} else {
fmt.Println("Actual: tree.New(1) != tree.New(2)")
}
}
/*
Slide 71: Web Crawler
*/
package main
import (
"fmt"
)
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)
}
var found map[string]string
func CrawlImpl(url string, fetcher Fetcher, ch chan []string) {
// prevent fetching twice
_, exists := found[url]
if !exists {
found[url] = "error" // initialize to error
body, urls, err := fetcher.Fetch(url) // do the fetch
ch <- urls
if err != nil {
fmt.Println(err)
} else {
found[url] = body
fmt.Printf("found: %s %q\n", url, body)
}
} else {
ch <- nil // no new urls to crawl
}
}
func Crawl(url string, unused int, fetcher Fetcher) {
urls := make(chan []string)
go CrawlImpl(url, fetcher, urls)
running := 1
for ; running > 0 ; {
newUrls := <- urls
running--
for i := 0; i < len(newUrls); i++ {
go CrawlImpl(newUrls[i], fetcher, urls)
running++
}
}
}
func main() {
found = make(map[string]string)
Crawl("http://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{
"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