Skip to content

Instantly share code, notes, and snippets.

@rorcraft
Last active December 11, 2015 18:19
Show Gist options
  • Save rorcraft/4640854 to your computer and use it in GitHub Desktop.
Save rorcraft/4640854 to your computer and use it in GitHub Desktop.
Golang Tutorial Exercies. http://tour.golang.org
/* #44 */
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := float64(1)
var diff float64
for {
diff = (z - (z*z - x)/2*z)
if diff < 0.1 {
z -= 0.1
break
}
z += 0.1
}
return z
}
func main() {
fmt.Println(Sqrt(4))
fmt.Println(math.Sqrt(4))
}
/* #45 Maps */
package main
import (
"tour/wc"
"fmt"
"strings"
)
func WordCount(s string) map[string]int {
words := strings.Fields(s)
counts := make(map[string]int)
for i := 0; i < len(words); i++ {
_, present := counts[words[i]]
if (present) {
counts[words[i]] += 1
}else{
counts[words[i]] = 1
}
}
fmt.Println()
return counts
}
func main() {
wc.Test(WordCount)
}
/* #46 Slices */
package main
import "tour/pic"
func Pic(dx, dy int) [][]uint8 {
picture := make([][]uint8, dy)
for i := 0; i < dy ; i++ {
picture[i] = make([]uint8, dx)
for j := 0; j < dx; j++ {
picture[i][j] = uint8(i^j)
}
}
return picture
}
func main() {
pic.Show(Pic)
}
/* 47 fibonacci */
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a := 0
b := 0
return func() int {
var n int
if (a == 0 && b == 0) {
n = 1
}else{
n = a + b
}
a = b
b = n
return n
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
# 57 Web server
package main
import (
"fmt"
"net/http"
)
type Struct struct {
Greeting string
Punct string
Who string
}
func (s Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s.Greeting + s.Punct + " " + s.Who )
}
type String string
func (s String) 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)
}
# Binary Tree
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) {
_walk(t, ch)
close(ch)
}
func _walk(t *tree.Tree, ch chan int) {
if t != nil {
_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 {
c1 := make(chan int)
c2 := make(chan int)
go Walk(t1, c1)
go Walk(t2, c2)
for i := range c1 {
if i != <-c2 {
return false
}
}
return true
}
func main() {
fmt.Println(tree.New(1))
ch := make(chan int)
go Walk(tree.New(2), ch)
//x := <-ch
for i := range ch {
fmt.Println(i)
}
fmt.Println(Same(tree.New(1), tree.New(1)))
fmt.Println(Same(tree.New(2), tree.New(1)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment