Skip to content

Instantly share code, notes, and snippets.

@squarism
Last active August 29, 2015 14:03
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 squarism/2384c44b40120bc4bb0d to your computer and use it in GitHub Desktop.
Save squarism/2384c44b40120bc4bb0d to your computer and use it in GitHub Desktop.
Go Tour Excercies
// Exercise 25 - Loops and Functions
// --------------------------------------------------------------------
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := 1.0
for i := 0; i < 10000000; i += 1 {
z = z - (math.Pow(z, 2) - x) / 2.0*z
}
return z
}
func main() {
fmt.Println(Sqrt(2))
}
// => 1.4141017458848133
// Exercise 38 - Slices
// --------------------------------------------------------------------
package main
import "code.google.com/p/go-tour/pic"
func Pic(dx, dy int) [][]uint8 {
buffer := make([][]uint8, dy)
for y := range buffer {
buffer[y] = make([]uint8, dx)
for x := range buffer[y] {
buffer[y][x] = uint8(x) ^ uint8(y)
}
}
return buffer
}
func main() {
pic.Show(Pic)
}
// => (an image appears on the go tour website)
// Exercise 43 - Maps
// --------------------------------------------------------------------
package main
import (
"code.google.com/p/go-tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
counts := make(map[string]int)
for _, word := range strings.Fields(s) {
counts[word] += 1
}
return counts
}
func main() {
wc.Test(WordCount)
}
// PASS
// Exercise 46 - Fibonacci
// --------------------------------------------------------------------
// TODO: I do not grok this. So I reverse the for loop to remind myself
// that i is not needed as an argument. The key point here is that x,y,z
// persist in the closure scope (i think).
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
x := 0
y := 1
z := 0
return func() int {
z, x, y = x, y, x+y
return z
}
}
func main() {
f := fibonacci()
for i := 10; i > 0; i-- {
fmt.Println(f())
}
}
// Exercise 50 - Complex Cube Roots
// --------------------------------------------------------------------
package main
import (
"fmt"
"math/cmplx"
)
func Cbrt(x complex128) complex128 {
z := complex128(5.0)
for i := 0; i < 10; i++ {
z = z - (cmplx.Pow(z, 3) - x) / (3 * (cmplx.Pow(z, 2)))
}
return z
}
func main() {
fmt.Println(Cbrt(2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment