From: sgf Date: Tue, 21 Jun 2022 21:20:59 +0000 (+0300) Subject: Tour of go solutions. X-Git-Url: https://gitweb.sgf-dma.tk/?a=commitdiff_plain;h=0e34fba21c65f112e426b652f8170fab4ab3f94d;p=go.git Tour of go solutions. --- diff --git a/tour.go b/tour.go new file mode 100644 index 0000000..d2aa46b --- /dev/null +++ b/tour.go @@ -0,0 +1,142 @@ +func myPrint(i interface{}) string { + switch v := i.(type) { + case fmt.Stringer: + return "made by Stringer " + v.String() + default: + return "a huy ego znait.." + } +} + + +func myPrint(i interface{}) string { + switch v := i.(type) { + case fmt.Stringer: + return "made by Stringer " + v.String() + case error: + return "Huh, that's an error " + v.Error() + + default: + return "a huy ego znait.." + } +} + +func Sqrt(x float64) float64 { + z := 1.0 + y := 0.0 + for i := 0; i < 10 && z != x*x && z != y; i++ { + fmt.Println(i, z) + y = z + z -= (z*z - x) / (2*z) + } + return z +} + +type ErrNegativeSqrt float64 + +func (e *ErrNegativeSqrt) Error() string { + return fmt.Sprintf("cannot Sqrt negative number: %v", *e) +} + +func Sqrt(x float64) (float64, error) { + z := 1.0 + y := 0.0 + if x < 0 { + return 0, (*ErrNegativeSqrt)(&x) + } + for i := 0; i < 10 && z != x*x && z != y; i++ { + fmt.Println(i, z) + y = z + z -= (z*z - x) / (2 * z) + } + return z, nil +} + +type MyReader struct{} + +func (r MyReader) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + x, y := p[:0], p[:] + p[0] = byte('A') + + l := 1 + for m := 1; l < len(p); l += m { + x = x[:len(x)+m] + y = y[m:] + m = copy(y, x) + } + return l, nil +} + + +func (MyReader) Read(b []byte) (int, error) { + b[0] = 'A' + x := b[:1] + y := b[1:] + //fmt.Printf("%q\n", x) + n := 0 + //fmt.Printf("x = %d, %v, y = %d, %v\n", len(x), x, len(y), y) + for len(y) > 0 { + n = copy(y, x) + //fmt.Printf("A: %v %v\n", x, y) + y = y[n:] + x = x[:len(x)+n] + //fmt.Printf("%d: x = %d, %v, y = %d, %v\n", n, len(x), x, len(y), y) + } + //fmt.Printf("%d: x = %d, %v, y = %d, %v\n", n, len(x), x, len(y), y) + return len(b), nil +} +package main + +import ( + "io" + "os" + "unicode" + "strings" +) + +type rot13Reader struct { + r io.Reader +} + +var rot13U string = "NOPQRSTUVWXYZABCDEFGHIJKLM" +var rot13L string = "nopqrstuvwxyzabcdefghijklm" + +func (v rot13Reader) Read(b []byte) (int, error) { + n, err := v.r.Read(b) + if err != nil { return n, err } + for i := 0; i < n; i++ { + c := rune(b[i]) + if !unicode.IsLetter(c) { + continue + } + if unicode.IsLower(c) { + j := b[i] - 'a' + b[i] = rot13L[j] + } else { + j := b[i] - 'A' + b[i] = rot13U[j] + } + + } + return n, nil +} + +func main() { + s := strings.NewReader("Lbh penpxrq gur pbqr!") + r := rot13Reader{s} + io.Copy(os.Stdout, &r) +} + +func Pic(dx, dy int) (img [][]uint8) { + img = make([][]uint8, dy) + for y := 0; y < dy; y++ { + img[y] = make([]uint8, dx) + for x := 0; x < dx; x++ { + img[y][x] = uint8(x*y) + } + } + return +} +