Skip to content

Instantly share code, notes, and snippets.

@cantino
Last active December 18, 2015 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cantino/5762586 to your computer and use it in GitHub Desktop.
Save cantino/5762586 to your computer and use it in GitHub Desktop.
Some practice Go programs.
package main
import "code.google.com/p/go-tour/pic"
func Pic(dx, dy int) [][]uint8 {
pic := make([][]uint8, dx)
for i := range(pic) {
pic[i] = make([]uint8, dy)
for j := range(pic[i]) {
pic[i][j] = uint8((i + j)/2)
}
}
return pic
}
func main() {
pic.Show(Pic)
}
package main
import (
"strings"
"code.google.com/p/go-tour/wc"
)
func WordCount(s string) map[string]int {
m := make(map[string]int)
for _, field := range(strings.Fields(s)) {
m[field]++
}
return m
}
func main() {
wc.Test(WordCount)
}
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) {
if t.Left != nil {
Walk(t.Left, ch)
}
ch <- t.Value
if t.Right != nil {
Walk(t.Right, ch)
}
}
// Same determines whether the trees
// t1 and t2 contain the same values.
// I think there's a better way to do this.
func Same(t1, t2 *tree.Tree) bool {
c1 := make(chan int)
c2 := make(chan int)
go func() { Walk(t1, c1); close(c1) }()
go func() { Walk(t2, c2); close(c2) }()
for v := range(c1) {
if v != <-c2 {
return false
}
}
return true
}
func main() {
fmt.Println(Same(tree.New(1), tree.New(1)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment