Skip to content

Instantly share code, notes, and snippets.

@CarlosLanderas
Last active February 4, 2024 07:49
Show Gist options
  • Save CarlosLanderas/11b4f6727deec051883ddc02edf5cd0b to your computer and use it in GitHub Desktop.
Save CarlosLanderas/11b4f6727deec051883ddc02edf5cd0b to your computer and use it in GitHub Desktop.
A Tour of Go (https://tour.golang.org) - Exercise Solutions
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
z := float64(1.5)
val := float64(0)
for {
z = z - (z*z-x)/(2*z)
if math.Abs(val-z) < 1e-10 {
break
}
val = z
}
return val, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
//Let's have some fun with functions.
//Implement a fibonacci function that returns a function (a closure) that returns successive fibonacci numbers (0, 1, 1, 2, 3, 5, ...).
package main
import "fmt"
func fibonacci() func() int {
prev := 0
curr := 1
return func() int {
prev, curr = curr, prev+curr
return curr
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
//As a simple way to play with functions and loops, implement the square
// root function using Newton's method.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := float64(1.5)
val := float64(0)
for {
z = z - (z*z-x)/(2*z)
if math.Abs(val-z) < 1e-10 {
break
}
val = z
}
return val
}
func main() {
fmt.Println(Sqrt(2))
}
//Implement a Reader type that emits an infinite stream of the ASCII character 'A'.
package main
import "golang.org/x/tour/reader"
type MyReader struct{}
func (MyReader) Read(b []byte) (n int, err error) {
for i := 0; i < len(b); i++ {
//You can either use 65 or 'A'
b[i] = 65
}
return len(b), nil
}
func main() {
reader.Validate(MyReader{})
}
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (rot *rot13Reader) Read(b []byte) (n int, err error) {
n, err = rot.r.Read(b)
for i := 0; i < len(b); i++ {
if (b[i] >= 'A' && b[i] < 'N') || (b[i] >= 'a' && b[i] < 'n') {
b[i] += 13
} else if (b[i] > 'M' && b[i] <= 'Z') || (b[i] > 'm' && b[i] <= 'z') {
b[i] -= 13
}
}
return
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
//Implement Pic. It should return a slice of length dy, each element of which is a slice of dx 8-bit unsigned integers. When you run the program, it will display your picture, interpreting the integers as grayscale (well, bluescale) values.
//The choice of image is up to you. Interesting functions include (x+y)/2, x*y, and x^y.
//(You need to use a loop to allocate each []uint8 inside the [][]uint8.)
//(Use uint8(intValue) to convert between types.)
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
sl := make([][]uint8, dy)
for i := range sl {
sl[i] = make([]uint8, dx)
for j := 0; j < dx; j++ {
sl[i][j] = uint8((i+j)/2 + i ^ j)
}
}
return sl
}
func main() {
pic.Show(Pic)
}
//Make the IPAddr type implement fmt.Stringer to print the address as a dotted quad.
//For instance, IPAddr{1, 2, 3, 4} should print as "1.2.3.4".
package main
import "fmt"
type IPAddr [4]byte
func (ipAddr IPAddr) String() string {
return fmt.Sprintf("%v.%v.%v.%v", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[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)
}
}
//Implement WordCount. It should return a map of the counts of each “word” in the string s.
//The wc.Test function runs a test suite against the provided function and prints success or failure.
package main
import (
"strings"
"golang.org/x/tour/wc"
)
func WordCount(s string) map[string]int {
m := make(map[string]int)
words := strings.Split(s, " ")
for _, v := range words {
_, ok := m[v]
if !ok {
m[v] = 1
} else {
m[v] += 1
}
}
return m
}
func main() {
wc.Test(WordCount)
}
@carlosalbaladejo
Copy link

carlosalbaladejo commented Nov 29, 2020

I leave here the exercise for images using your Pic function. Feel free to add it to your list

package main

import (
	"golang.org/x/tour/pic"
	"image"
	"image/color"
)

type Image struct{
	pixels [][]color.Color
}

func (Image) ColorModel() color.Model {
	return color.RGBAModel
}

func (i Image) Bounds() image.Rectangle {
	return image.Rect(0,0, len(i.pixels[0]), len(i.pixels))
}

func (i Image) At(x, y int) color.Color {
	return i.pixels[y][x]
}

func Pic(dx, dy int) [][]color.Color {
	sl := make([][]color.Color, dy)
	for i := range sl {
		sl[i] = make([]color.Color, dx)
		for j := 0; j < dx; j++ {
			sl[i][j] = color.RGBA{uint8((i+j)/2 + i ^ j), uint8((i+j)/2 + i ^ j), 255, 255}
		}
	}
	return sl
}

func main() {
	m := Image{Pic(50,100)}
	pic.ShowImage(m)
}

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