Last active
August 29, 2015 13:56
-
-
Save jsoriano/9060536 to your computer and use it in GitHub Desktop.
Some exercises of go tour
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
// Equivalent Binary Trees | |
package main | |
import "code.google.com/p/go-tour/tree" | |
import "fmt" | |
func Walk(t *tree.Tree, ch chan int) { | |
defer close(ch) | |
var walk func(t *tree.Tree) | |
walk = func(t *tree.Tree) { | |
if t == nil { return } | |
walk(t.Left) | |
ch <- t.Value | |
walk(t.Right) | |
} | |
walk(t) | |
} | |
func Same(t1, t2 *tree.Tree) bool { | |
channel1 := make(chan int) | |
channel2 := make(chan int) | |
go Walk(t1, channel1) | |
go Walk(t2, channel2) | |
for n1 := range channel1 { | |
n2, more := <- channel2 | |
if !more || n1 != n2 { | |
return false | |
} | |
} | |
_, more := <- channel2 | |
return ! more | |
} | |
func main() { | |
channel := make(chan int) | |
go Walk(tree.New(1), channel) | |
for n := range channel { | |
fmt.Println(n) | |
} | |
fmt.Println(Same(tree.New(1), tree.New(1))) | |
fmt.Println(Same(tree.New(1), tree.New(2))) | |
} |
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
// Rot13 Reader Go tour | |
package main | |
import ( | |
"io" | |
"os" | |
"strings" | |
) | |
type rotReader struct { | |
r io.Reader | |
n int | |
} | |
func rotbyte(b byte, min, max byte, n int) byte { | |
modulus := (max - min + 1) | |
return ((b - min + byte(n)) % modulus) + min | |
} | |
func rot(b byte, n int) byte { | |
switch { | |
case b >= 'A' && b <= 'Z': | |
return rotbyte(b, 'A', 'Z', 13) | |
case b >= 'a' && b <= 'z': | |
return rotbyte(b, 'a', 'z', 13) | |
default: | |
return b | |
} | |
} | |
func (r rotReader) Read(p []byte) (n int, err error) { | |
n, err = r.r.Read(p) | |
for i := 0; i < n; i++ { | |
p[i] = rot(p[i], r.n) | |
} | |
return | |
} | |
func main() { | |
s := strings.NewReader( | |
"Lbh penpxrq gur pbqr!") | |
r := rotReader{s, 13} | |
io.Copy(os.Stdout, &r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment