-
Notifications
You must be signed in to change notification settings - Fork 1
/
shape.go
130 lines (103 loc) · 1.89 KB
/
shape.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package main
import (
"fmt"
"math"
)
type Shape interface {
Area() float64
MoveBy(dx, dy int)
BasePoint() *Point
}
type Shapes []Shape
func (s Shapes) Biggest() Shape {
var biggest Shape
for _, sh := range s {
if biggest == nil || sh.Area() > biggest.Area() {
biggest = sh
}
}
return biggest
}
func (s Shapes) Points() Points {
r := Points{}
for _, i := range s {
if !r.Include(i.BasePoint()) {
r = append(r, i.BasePoint())
}
}
return r
}
func (s Shapes) MoveBy(dx, dy int) {
for _, p := range s.Points() {
p.MoveBy(dx, dy)
}
}
type Point struct {
Px, Py int
}
func (p *Point) MoveBy(dx, dy int) {
p.Px += dx
p.Py += dy
}
func (p *Point) GoString() string {
return fmt.Sprintf("Point{Px: %d, Py: %d}", p.Px, p.Py)
}
type Points []*Point
func (s Points) Include(p *Point) bool {
for _, i := range s {
if i == p {
return true
}
}
return false
}
type Circle struct {
radius int
Point *Point
}
var _ Shape = (*Circle)(nil)
func NewCircle(p *Point, r int) *Circle {
return &Circle{Point: p, radius: r}
}
func (c *Circle) BasePoint() *Point {
return c.Point
}
func (c *Circle) Expand(dr int) {
c.radius += dr
}
func (c *Circle) Area() float64 {
return math.Pi * float64(c.radius*c.radius)
}
func (c *Circle) MoveBy(dx, dy int) {
c.Point.MoveBy(dx, dy)
}
func (c *Circle) GoString() string {
return fmt.Sprintf("%#v", *c)
}
type Rect struct {
width, length int
Point *Point
}
var _ Shape = (*Rect)(nil)
func (c *Rect) BasePoint() *Point {
return c.Point
}
func (r *Rect) Area() float64 {
return float64(r.width * r.length)
}
func (r *Rect) MoveBy(dx, dy int) {
r.Point.MoveBy(dx, dy)
}
func (r *Rect) GoString() string {
return fmt.Sprintf("%#v", *r)
}
type RectList []*Rect
func (s RectList) Biggest() *Rect {
var biggest *Rect
for _, r := range s {
if biggest == nil || r.Area() > biggest.Area() {
biggest = r
}
}
return biggest
}