Compare commits

..

1 Commits

Author SHA1 Message Date
08f7db87ad Day 3: spiral 2017-12-03 18:20:57 +01:00

View File

@ -13,6 +13,17 @@ const (
S
)
var (
cur int
x int
y int
dir int
xmax int
xmin int
ymax int
ymin int
)
func main() {
n, err := strconv.Atoi(os.Args[1])
if err != nil {
@ -20,6 +31,65 @@ func main() {
}
fmt.Println(n)
cur, x, y, dir, width, height := 1, 0, 0, W
// create cell and compute change direction, expand grid
for cur < n {
nextMove()
fmt.Println(cur, x, y)
}
fmt.Println("\n", Abs(x)+Abs(y))
}
func nextMove() {
if cur == 0 {
dir = S
} else {
x1, y1 := dirMove()
if outOfBound(x1, y1) {
changeDir()
x1, y1 = dirMove()
}
x, y = x1, y1
}
cur++
}
func dirMove() (int, int) {
switch dir {
case W:
return x - 1, y
case N:
return x, y + 1
case E:
return x + 1, y
case S:
return x, y - 1
default:
return x, y
}
}
func outOfBound(x1 int, y1 int) bool {
return x1 > xmax || x1 < xmin || y1 > ymax || y1 < ymin
}
func changeDir() {
switch dir {
case W:
dir = S
ymin--
case N:
dir = W
xmin--
case E:
dir = N
ymax++
case S:
dir = E
xmax++
}
}
func Abs(n int) int {
if n < 0 {
return -n
}
return n
}