Skip to content

Instantly share code, notes, and snippets.

@inancgumus
Last active August 23, 2023 10:58
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inancgumus/d25d045b4cec43dcbb111e04980d396b to your computer and use it in GitHub Desktop.
Save inancgumus/d25d045b4cec43dcbb111e04980d396b to your computer and use it in GitHub Desktop.
go tour exercise solutions
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
p := make([][]uint8, dy)
for y := range p {
p[y] = make([]uint8, dx)
for x := 0; x < dx; x++ {
p[y][x] = uint8(x^y)
}
}
return p
}
func main() {
pic.Show(Pic)
}
package main
import "fmt"
type IPAddr [4]byte
// TODO: Add a "String() string" method to IPAddr.
func (ip IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", ip[0], ip[1],
ip[2], ip[3])
}
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 (
"fmt"
"math"
)
type NegativeSqrt float64
func (e NegativeSqrt) Error() string {
return fmt.Sprint(float64(e))
}
func (e NegativeSqrt) String() string {
return fmt.Sprintf("%f", e)
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, NegativeSqrt(x)
}
return math.Sqrt(x), nil
}
func main() {
fmt.Println(Sqrt(-2))
fmt.Println(Sqrt(2))
}
package main
import "golang.org/x/tour/reader"
type MyReader struct{}
func (r MyReader) Read(buf []byte) (int, error) {
buf[0] = 'A'
return 1, nil
}
func main() {
reader.Validate(MyReader{})
}
package main
import (
"golang.org/x/tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
wo := strings.Fields(s)
c := make(map[string]int, len(wo))
for _, w := range wo {
c[w] += 1
}
return c
}
func main() {
wc.Test(WordCount)
}
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
in io.Reader
}
func (rot *rot13Reader) Read(p []byte) (n int, err error) {
n, err = rot.in.Read(p)
for i, c := range p {
switch {
case c >= 'A' && c <= 'M' || c >= 'a' && c <= 'm':
p[i] += 13
case c >= 'N' && c <= 'Z' || c >= 'n' && c <= 'z':
p[i] -= 13
}
}
return
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
package main
import (
"image"
"image/color"
"math/rand"
"time"
"golang.org/x/tour/pic"
)
type Image struct {
Width, Height int
colr uint8
}
func (r *Image) Bounds() image.Rectangle {
return image.Rect(0, 0, r.Width, r.Height)
}
func (r *Image) ColorModel() color.Model {
return color.RGBAModel
}
func (r *Image) At(x, y int) color.Color {
return color.RGBA{
randUint8(x%255, 255),
randUint8(0, y%255+1),
randUint8(0, (x^y)%255+1),
randUint8(200, 255)}
}
func randUint8(min int, max int) uint8 {
return uint8(min + rand.Intn(max - min))
}
func init() {
rand.Seed(time.Now().UTC().UnixNano())
}
func main() {
m := Image{500, 500, 0}
pic.ShowImage(&m)
}
package main
import "fmt"
func fibonacci() func() int {
first, second := 0, 1
return func() int {
previousFirst := first
first, second = second, first + second
return previousFirst
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
package main
import (
"fmt"
"golang.org/x/tour/tree"
)
type ch chan int
// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch ch) {
defer close(ch)
var w func(t *tree.Tree)
w = func(t *tree.Tree) {
if t != nil {
w(t.Right)
ch <- t.Value
w(t.Left)
}
}
w(t)
}
// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
c1, c2 := make(ch), make(ch)
go Walk(t1, c1)
go Walk(t2, c2)
for v := range c1 {
if v != <-c2 {
return false
}
}
return true
}
func main() {
ch := make(ch)
go Walk(tree.New(1), ch)
for v := range ch {
fmt.Println(v, " ")
}
fmt.Println("Same?", Same(tree.New(1), tree.New(1)))
fmt.Println("Same?", Same(tree.New(1), tree.New(2)))
}
package main
import (
"fmt"
)
// Newton's method is to approximate Sqrt(x) by
// picking a starting point z first, and repeating.
func Sqrt(x float64) float64 {
z := 1.0
for i := 0; i < 10; i++ {
fmt.Printf("(%f) / (%f)\n", z*z - x, 2*z)
z -= (z*z - x) / (2*z)
}
return z
}
func main() {
fmt.Println(Sqrt(16))
}
@denis-trofimov
Copy link

Thank you for your work! 👍
https://gist.github.com/inancgumus/d25d045b4cec43dcbb111e04980d396b#file-exercise_23_rot13-go-L15
Here is a flaw the same I made before.
Try fmt.Println(p) in the loop and see a bunch of zeros you check after the final 21st symbol.
It also runs slower than should.
One way to deal is

func (rot *rot13Reader) Read(b []byte) (int, error) {
	len, err := rot.r.Read(b)


	for i := 0; i < len; i++ {
		if b[i] >= 'A' && b[i] <= 'M' || b[i] >= 'a' && b[i] <= 'm' {
			b[i] += 13
		} else if b[i] >= 'N' && b[i] <= 'Z' || b[i] >= 'n' && b[i] <= 'z' {
			b[i] -= 13
		}
		// No extra buffer reading occur like then using "range b" before.
		fmt.Println(b[i])
	}


	return len, err
}

https://github.com/denis-trofimov/golang_tour/blob/master/exercise-rot13-reader.go#L14-L28

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment