Skip to content

Instantly share code, notes, and snippets.

@bluSch
Created September 17, 2012 22:35
Show Gist options
  • Save bluSch/3740207 to your computer and use it in GitHub Desktop.
Save bluSch/3740207 to your computer and use it in GitHub Desktop.
Solutions for tour.golang exercises
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z, d := 1.0, 1.0
for d > 1e-4 { //more precise than 1e-4 fails online
zz := z
z = z-(z*z-x)/2*z
d = math.Abs(z-zz)
}
return z
}
func main() {
fmt.Println(Sqrt(2), math.Sqrt(2))
}
package main
import (
"tour/wc"
"strings"
)
func WordCount(s string) map[string]int {
fields := strings.Fields(s)
counts := make(map[string]int)
for _, word := range fields {
counts[word]++
}
return counts
}
func main() {
wc.Test(WordCount)
}
package main
import "tour/pic"
func Pic(dx, dy int) [][]uint8 {
slices := make([][]uint8, dy)
for i := 0; i < dy; i++ {
slices[i] = make([]uint8, dx)
for j := 0; j < dx; j++ {
slices[i][j] = uint8(i^j)
}
}
return slices
}
func main() {
pic.Show(Pic)
}
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 {
next := fib1
fib1 = fib1+fib2
fib2 = next
return fib1
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
package main
import (
"fmt"
"math/cmplx"
)
func Cbrt(x complex128) complex128 {
z := complex128(1.0)
d := 1.0
for d > 1e-17 {
zz := z
z = z-(cmplx.Pow(z, 3)-x)/(3*cmplx.Pow(z, 2))
d = cmplx.Abs(z-zz)
}
return z
}
func main() {
fmt.Println(Cbrt(2))
}
package main
import (
"net/http"
"fmt"
)
type String string
type Struct struct {
Greeting string
Punct string
Who string
}
func (s String) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s)
}
func (s Struct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, s)
}
func main() {
// your http.Handle calls here
http.Handle("/string", String("I'm a frayed knot."))
http.Handle("/struct", &Struct{"Hello", ":", "Gophers!"})
http.ListenAndServe("localhost:4000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment