From 4b22135336213f2a972e1bf3fac29083a50ee95a Mon Sep 17 00:00:00 2001 From: David Ashby Date: Thu, 2 Dec 2021 12:59:40 -0500 Subject: [PATCH] day 2 --- 02/main.go | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 02/main.go diff --git a/02/main.go b/02/main.go new file mode 100644 index 0000000..a4b2f54 --- /dev/null +++ b/02/main.go @@ -0,0 +1,74 @@ +package main + +import ( + "bufio" + "fmt" + "os" + "strconv" + "strings" + "time" +) + +func main() { + start := time.Now() + partOne() + duration := time.Since(start) + partTwo() + duration2 := time.Since(start) + fmt.Printf("p1: %s, p2: %s\n", duration, duration2-duration) +} + +func makeScanner(test bool) *bufio.Scanner { + var f *os.File + if test { + f, _ = os.Open("inputs/testinput") + } else { + f, _ = os.Open("inputs/input") + } + reader := bufio.NewReader(f) + return bufio.NewScanner(reader) +} + +func mustAtoi(line string) int { + i, _ := strconv.Atoi(line) + return i +} + +func partOne() { + scanner := makeScanner(false) + + var up, down, forward int + for scanner.Scan() { + line := scanner.Text() + dir, i := strings.Split(line, " ")[0], mustAtoi(strings.Split(line, " ")[1]) + switch dir { + case "forward": + forward += i + case "down": + down += i + case "up": + up += i + } + } + fmt.Println(forward * (down - up)) +} + +func partTwo() { + scanner := makeScanner(false) + + var horizontal, vertical, aim int + for scanner.Scan() { + line := scanner.Text() + dir, i := strings.Split(line, " ")[0], mustAtoi(strings.Split(line, " ")[1]) + switch dir { + case "forward": + horizontal += i + vertical += (i * aim) + case "down": + aim += i + case "up": + aim -= i + } + } + fmt.Println(horizontal * vertical) +}