Skip to content

Instantly share code, notes, and snippets.

@soffes
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save soffes/0509f6bec7b40cc8b171 to your computer and use it in GitHub Desktop.

Select an option

Save soffes/0509f6bec7b40cc8b171 to your computer and use it in GitHub Desktop.
Learn Go Exercises — http://tour.golang.org
// #25 — Loops and Functions
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := 1.0
c := 0.0
for i := 1.0; i <= 20; i++ {
change := (z*z - x) / (2.0 * z)
if change == c {
return z
}
z -= change
c = change
}
return z
}
func main() {
var input float64 = 5
fmt.Printf("math.Sqrt: %v\n", math.Sqrt(input))
fmt.Printf(" my Sqrt: %v\n", Sqrt(input))
}
// #38 — Slices
package main
import "code.google.com/p/go-tour/pic"
func Pic(dx, dy int) [][]uint8 {
output := make([][]uint8, dx)
for x := 0; x < dx; x++ {
output[x] = make([]uint8, dy)
for y := 0; y < dy; y++ {
output[x][y] = uint8(x^y)
}
}
return output
}
func main() {
pic.Show(Pic)
}
// #43 — Maps
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
m := make(map[string]int)
for _, v := range strings.Fields(s) {
if mv, ok := m[v]; ok {
m[v] = mv + 1
} else {
m[v] = 1
}
}
return m
}
func main() {
wc.Test(WordCount)
}
// #46 = Fibonacci closure
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
f0 := 0
f1 := 1
fn := f0
return func() int {
fn = f0 + f1
f0 = f1
f1 = fn
return fn
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
// #50 — Complex cube roots
package main
import (
"fmt"
"math/cmplx"
)
func Cbrt(x complex128) complex128 {
var z complex128 = 1
var c complex128 = 0
for i := 1.0; i <= 20; i++ {
change := (cmplx.Pow(z, 3) - x) / (3 * cmplx.Pow(z, 2))
if change == c {
return z
}
z -= change
c = change
}
return z
}
func main() {
fmt.Println(Cbrt(2))
}
// #58 — 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 := 1.0
c := 0.0
for i := 1.0; i <= 20; i++ {
change := (z*z - x) / (2.0 * z)
if change == c {
return z, nil
}
z -= change
c = change
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
// #60 — HTTP Handlers
package main
import (
"fmt"
"net/http"
)
type String string
func (s String) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, s)
}
type Struct struct {
Greeting string
Punct string
Who string
}
func (s Struct) ServeHTTP(
w http.ResponseWriter,
r *http.Request) {
fmt.Fprint(w, s)
}
func main() {
http.Handle("/string", String("I'm a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
http.ListenAndServe("localhost:4000", nil)
}
// #62 — Images
package main
import (
"code.google.com/p/go-tour/pic"
"image"
"image/color"
)
type Image struct{}
func (i Image) Bounds() image.Rectangle {
return image.Rect(0, 0, 256, 256)
}
func (i Image) ColorModel() color.Model {
return color.RGBAModel
}
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)
}
// #63 — Rot13 Reader
// Struggled with this for a long time. Went down the path of working with UTF8 runes and whatnot.
// Got really discouraged. Googled up a solution and was really impressed with how easy it actually
// was. Totally makes sense since ROT13 only works with ASCII. Anyway, solution by @zyxar for this
// one.
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (rot *rot13Reader) Read(p []byte) (n int, err error) {
n,err = rot.r.Read(p)
for i := 0; i < len(p); i++ {
if (p[i] >= 'A' && p[i] < 'N') || (p[i] >='a' && p[i] < 'n') {
p[i] += 13
} else if (p[i] > 'M' && p[i] <= 'Z') || (p[i] > 'm' && p[i] <= 'z'){
p[i] -= 13
}
}
return
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
// #72 — Equivalent Binary Trees
package main
import (
"fmt"
"reflect"
"code.google.com/p/go-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) {
_walk(t, ch)
close(ch)
}
func _walk(t *tree.Tree, ch chan int) {
if t == nil {
return
}
// I'd love to make the recursive calls goroutines, but
// I couldn't figure out how to know I was done.
_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, 10)
ch2 := make(chan int, 10)
v1 := make(map[int]bool)
v2 := make(map[int]bool)
go Walk(t1, ch1)
for v := range ch1 {
v1[v] = true
}
go Walk(t2, ch2)
for v := range ch2 {
v2[v] = true
}
// There's probably a better way to compare these
return reflect.DeepEqual(v1, v2)
}
func main() {
fmt.Printf("1 == 1: %v\n", Same(tree.New(1), tree.New(1)))
fmt.Printf("1 == 2: %v\n", Same(tree.New(1), tree.New(2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment