Skip to content

Instantly share code, notes, and snippets.

@andradei
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andradei/f8e8620da762dc294aa2 to your computer and use it in GitHub Desktop.
Save andradei/f8e8620da762dc294aa2 to your computer and use it in GitHub Desktop.
Go Tour Exercises 2015
package main
import (
"fmt"
)
func Sqrt(x float64) float64 {
z := float64(x)
delta := 10.0
var temp float64
tolerance := 0.00000001
// Arbitrarilly returns 0 for negative numbers too
if x <= 0 { return 0 }
for tolerance < delta {
temp = z
z = z - ((z * z - x) / (2 * z))
delta = temp - z
}
return z
}
func main() {
fmt.Println(Sqrt(-4)) // Arbitrarilly returns 0 for negative numbers
fmt.Println(Sqrt(0))
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(4))
fmt.Println(Sqrt(8))
fmt.Println(Sqrt(9))
fmt.Println(Sqrt(16))
fmt.Println(Sqrt(25))
fmt.Println(Sqrt(36))
fmt.Println(Sqrt(49))
fmt.Println(Sqrt(64))
fmt.Println(Sqrt(81))
fmt.Println(Sqrt(100))
}
package main
import "code.google.com/p/go-tour/pic"
func Pic(dx, dy int) [][]uint8 {
row := make([][]uint8, dy) // [][]uin8, len dy, cap dy
// Loop throught the rows and create columns
for y := range row {
row[y] = make([]uint8, dx)
// Make patterns
for x := range row[y] {
row[y][x] = uint8((y ^ x))
}
}
return row
}
func main() {
pic.Show(Pic)
}
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
string_array := strings.Fields(s)
word_map := make(map[string]int)
for _, v := range string_array {
_, ok := word_map[v]
if ok == false {
word_map[v] = 1
} else {
word_map[v] = word_map[v] + 1
}
}
return word_map
}
func main() {
wc.Test(WordCount)
}
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
fib1, fib2 := 0, 1
return func() int {
fib1, fib2 = fib2, fib1 + fib2
return fib2
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
package main
import "fmt"
type IPAddr [4]byte
func (ipAddr IPAddr) String() string {
return fmt.Sprintf("%d.%d.%d.%d", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3])
}
func main() {
addrs := map[string]IPAddr{
"loopback": {127, 0, 0, 1},
"googleDNS": {8, 8, 8, 8},
}
for n, a := range addrs {
fmt.Printf("%v: %v\n", n, a)
}
}
package main
import (
"fmt"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("Cannot Sqrt negative number: %v", float64(e))
}
func Sqrt(x float64) (float64, error) {
z := float64(x)
delta := 10.0
var temp float64
tolerance := 0.00000001
// Arbitrarilly returns 0 for negative numbers too
if x < 0 {return 0, ErrNegativeSqrt(x)}
for tolerance < delta {
temp = z
z = z - ((z * z - x) / (2 * z))
delta = temp - z
}
return z, nil
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
package main
import "code.google.com/p/go-tour/reader"
type MyReader struct{}
// TODO: Add a Read([]byte) (int, error) method to MyReader.
func (r MyReader) Read(b []byte) (int, error) {
b[0] = 'A'
return 1, nil
}
func main() {
reader.Validate(MyReader{})
}
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (rot rot13Reader) Read(b []byte) (i int, e error) {
i, e = 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)
}
package main
import (
"fmt"
"log"
"net/http"
)
type String string
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s)
}
type Struct struct {
Greeting string
Punct string
Who string
}
func (s Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s)
}
func main() {
// Set the handlers before you start the server
http.Handle("/string", String("I'm a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
// Starting the server is the last thing you do
// and checking for errors, of course
fmt.Println("Listening on localhost:4000")
err := http.ListenAndServe("localhost:4000", nil)
if err != nil {
log.Fatal(err)
}
}
package main
import (
"code.google.com/p/go-tour/pic"
"image"
"image/color"
)
type Image struct{
w, h int
color uint8
}
// Implement image.Image
func (i Image) ColorModel() color.Model {
return color.RGBAModel
}
func (i Image) Bounds() image.Rectangle {
return image.Rect(0, 0, i.w, i.h)
}
func (i Image) At(x, y int) color.Color {
return color.RGBA{i.color + uint8(x), i.color + uint8(y), 255, 255}
}
func main() {
m := Image{500,100, 155}
pic.ShowImage(m)
}
// This solution assumes the trees being compared by Same() are of
// equal number of leaves (nodes, or whatever you want to call them)
package main
import (
"code.google.com/p/go-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) {
_walk(t, ch)
close(ch)
}
// Private walk method, created to keep code DRY
// named _walk() to be more distinct to Walk()
func _walk(t *tree.Tree, ch chan int) {
// Return if walk reached end of tree
if (t == nil) {
return
}
// Make sure _walk() gets values in the right order
// Left value , this value, Right value
_walk(t.Left, ch)
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 {
// Make two channels to compare the tree values
ch1, ch2 := make(chan int), make(chan int)
// Don't wait for Walk() on both trees
go Walk(t1, ch1)
go Walk(t2, ch2)
// Block until channels receive data to b compared
// and compare each tree value in the same order
for i := range ch1 {
if i != <-ch2 {return false}
}
return true
}
func main() {
// 1)Test Walk()
ch := make(chan int)
// 1.1)Don't wait for Walk()
go Walk(tree.New(1), ch)
// 1.2)Wait for channel response
for i := range ch {
fmt.Println(i)
}
// Test Same()
fmt.Println(Same(tree.New(1), tree.New(1))) // has to print true
fmt.Println(Same(tree.New(1), tree.New(2))) // has to print false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment