Last active
December 18, 2015 09:39
-
-
Save cantino/5762586 to your computer and use it in GitHub Desktop.
Some practice Go programs.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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