Skip to content

Instantly share code, notes, and snippets.

@ololobus
Last active July 8, 2020 21:39
Show Gist options
  • Save ololobus/e1ae0bccb1dd7919099fab70255ef347 to your computer and use it in GitHub Desktop.
Save ololobus/e1ae0bccb1dd7919099fab70255ef347 to your computer and use it in GitHub Desktop.
A Tour of Go

A Tour of Go excersises

package main
import (
"golang.org/x/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) {
if t != nil {
Walk(t.Left, ch)
// fmt.Printf("\nReturning %d", t.Value)
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 {
ch1 := make(chan int)
ch2 := make(chan int)
res := true
defer close(ch1)
defer close(ch2)
go Walk(t1, ch1)
go Walk(t2, ch2)
for i := 0; i < 10; i++ {
v1, v2 := <- ch1, <- ch2
fmt.Printf("\nComparing %d and %d", v1, v2)
if v1 != v2 {
// TODO: How to gracefully stop recoursive goroutine?
res = false
}
}
return res
}
func main() {
ch := make(chan int, 10)
fmt.Println(tree.New(2).String())
defer close(ch)
go Walk(tree.New(1), ch)
// TODO: How to know that recoursive goroutine has finished and there will be no new results?
// With WaitGroup usage?
// See https://stackoverflow.com/questions/27103161/recursive-goroutines-what-is-the-neatest-way-to-tell-go-to-stop-reading-from-ch
for i := 0; i < 10; i++ {
fmt.Printf("\n%d", <- ch)
}
fmt.Printf("\n%s", fmt.Sprint(Same(tree.New(2), tree.New(2))))
fmt.Printf("\n%s", fmt.Sprint(Same(tree.New(2), tree.New(8))))
}
package main
import (
"fmt"
)
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
prev_prev, prev := 0, 1
return func() int {
next := prev_prev
prev_prev, prev = prev, prev_prev+prev
return next
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r *strings.Reader
}
func (rr rot13Reader) Read(res []byte) (int, error) {
b, err := rr.r.ReadByte()
b = []byte(strings.ToLower(string(b)))[0]
if b > 96 && b < 123 {
b = (b + 13 - 97) % (123 - 97) + 97
}
n := copy(res, []byte{b})
return n, err
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
package main
import "golang.org/x/tour/reader"
type MyReader struct{}
func (r MyReader) Read(res []byte) (int, error) {
copy(res, []byte("A"))
return 1, nil
}
// TODO: Add a Read([]byte) (int, error) method to MyReader.
func main() {
reader.Validate(MyReader{})
}
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
s := make([][]uint8, dx)
for ix := 0; ix < dx; ix++ {
s[ix] = make([]uint8, dy)
}
for ix := 0; ix < dx; ix++ {
for iy := 0; iy < dy; iy++ {
s[ix][iy] = uint8(ix^iy)
}
}
return s
}
func main() {
pic.Show(Pic)
}
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %s", fmt.Sprint(float64(e)))
}
func Sqrt(x float64) (float64, error) {
var z float64 = 1
var eps float64 = math.Pow(10, -15)
z_prev := 0.0
if x >= 0 {
for math.Abs(z_prev - z) >= eps {
z_prev = z
z -= (z*z - x) / (2*z)
fmt.Printf("%f -> %f\n", z_prev, z)
}
return z, nil
} else {
return 0, ErrNegativeSqrt(x)
}
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
var z float64 = 1
var eps float64 = math.Pow(10, -15)
z_prev := 0.0
for math.Abs(z_prev - z) >= eps {
z_prev = z
z -= (z*z - x) / (2*z)
fmt.Printf("%f -> %f\n", z_prev, z)
}
return z
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(math.Sqrt(2))
}
package main
import (
"fmt"
"strings"
)
type IPAddr [4]byte
// TODO: Add a "String() string" method to IPAddr.
func (ipa IPAddr) String() string {
var result []string
for _, v := range ipa {
result = append(result, fmt.Sprint(v))
}
return strings.Join(result, ".")
}
func main() {
hosts := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for name, ip := range hosts {
fmt.Printf("%v: %v\n", name, ip)
}
}
package main
import (
"golang.org/x/tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
ws := strings.Fields(s)
m := make(map[string]int)
for _, w := range ws {
_, ok := m[w]
if ok {
m[w] += 1
} else {
m[w] = 1
}
}
return m
}
func main() {
wc.Test(WordCount)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment