From 08f7db87ad8f3c27ad6e78f3b4a8f811a9a94f46 Mon Sep 17 00:00:00 2001 From: Meutel Date: Sun, 3 Dec 2017 12:19:25 +0100 Subject: [PATCH] Day 3: spiral --- 03dec/main.go | 95 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 03dec/main.go diff --git a/03dec/main.go b/03dec/main.go new file mode 100644 index 0000000..e419885 --- /dev/null +++ b/03dec/main.go @@ -0,0 +1,95 @@ +package main + +import ( + "fmt" + "os" + "strconv" +) + +const ( + W = iota + N + E + 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 { + os.Exit(1) + } + fmt.Println(n) + + // 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 +}