more exercises

This commit is contained in:
Ryan Cavicchioni 2020-02-09 10:44:41 -06:00
parent 4edd033ebd
commit 7ee04a1864
Signed by: ryanc
GPG Key ID: 877EEDAF9245103D
4 changed files with 110 additions and 0 deletions

28
exercise-errors.go Normal file
View File

@ -0,0 +1,28 @@
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}
func Sqrt(x float64) (float64, error) {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
var p float64
for z := 1.0; z != p && math.Abs(z - p) > 0.000000000000001; z -= (z * z - x) / (2 * z) {
p = z
}
return p, nil
}
func main() {
fmt.Println(Sqrt(4))
fmt.Println(Sqrt(-2))
}

19
exercise-reader.go Normal file
View File

@ -0,0 +1,19 @@
package main
import "golang.org/x/tour/reader"
type MyReader struct{}
// TODO: Add a Read([]byte) (int, error) method to MyReader.
func (MyReader) Read(b []byte) (int, error) {
c := "A"
for i := range b {
b[i] = byte(c[0])
}
return len(b), nil
}
func main() {
reader.Validate(MyReader{})
}

42
exercise-rot-reader.go Normal file
View File

@ -0,0 +1,42 @@
package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
var rot13Input []byte = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
var rot13Output []byte = []byte("NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm")
func indexOf(s []byte, b byte) int {
for i, v := range s {
if v == b {
return i
}
}
return -1
}
func (r rot13Reader) Read(b []byte) (n int, err error) {
n, err = r.r.Read(b)
if err == nil {
for i := 0; i < n; i++ {
c := b[i]
if j := indexOf(rot13Input, c); j > -1 {
b[i] = rot13Output[j]
}
}
}
return n, err
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}

21
reader.go Normal file
View File

@ -0,0 +1,21 @@
package main
import (
"fmt"
"io"
"strings"
)
func main() {
r := strings.NewReader("Hello, Reader!")
b := make([]byte, 8)
for {
n, err := r.Read(b)
fmt.Printf("n = %v err = %v b = %v\n", n, err, b)
fmt.Printf("b[:n] = %q\n", b[:n])
if err == io.EOF {
break
}
}
}