Skip to content

Instantly share code, notes, and snippets.

@cliffwoo
Forked from srid/44.go
Created January 12, 2013 02:49
Show Gist options
  • Save cliffwoo/4515794 to your computer and use it in GitHub Desktop.
Save cliffwoo/4515794 to your computer and use it in GitHub Desktop.
// Exercise: Loops and Functions - http://tour.golang.org/#44
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := 3.0
threshold := 0.0000000000001
for i := 0; ; i++ {
delta := (z*z - x)/(2*z)
if (delta < threshold) {
break
}
z -= delta
}
return z
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(math.Sqrt(2))
}
// Exercise: Maps - http://tour.golang.org/#45
package main
import (
"strings"
"tour/wc"
)
func WordCount(s string) (freq map[string]int) {
freq = make(map[string]int)
for _, word := range strings.Fields(s) {
freq[word] += 1
}
return
}
func main() {
wc.Test(WordCount)
}
// Exercise: Slices - http://tour.golang.org/#46
package main
import "tour/pic"
func Pic(dx, dy int) [][]uint8 {
p := make([][]uint8, dx)
for row := range p {
p[row] = make([]uint8, dy)
for col := range p[row] {
v := (2*row + 3*col)
p[row][col] = uint8(v)
}
}
return p
}
func main() {
pic.Show(Pic)
}
// Exercise: Fibonacci closure - - http://tour.golang.org/#47
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
a, b := 1, 0
return func() int{
a, b = b, a+b
return a
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
// Exercise: Equivalent Binary Trees - http://tour.golang.org/#69
package main
import "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){
Walk2(t, ch)
close(ch)
}
// better way using closures here, https://groups.google.com/forum/?fromgroups=#!topic/golang-nuts/gva8SmZGmek
func Walk2(t *tree.Tree, ch chan int){
if t.Left != nil {
Walk2(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
Walk2(t.Right, ch)
}
}
func SameChannel(ch1, ch2 chan int) bool{
for v1 := range ch1 {
//fmt.Println(v1)
v2, ok := <- ch2
//fmt.Println(v2)
if !ok || v1 != v2 {
return false
}
}
_, ok := <- ch2
//fmt.Println(ok)
return !ok
}
// 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)
return SameChannel(ch1, ch2)
}
func main() {
fmt.Println(Same(tree.New(2), tree.New(2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment