From c5a976fd9c7e40d70ad375a501dbf657a98979ab Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorben=20G=C3=BCnther?= Date: Sun, 5 Dec 2021 00:23:24 +0100 Subject: [PATCH] Solve day 2 part 2 --- day02/day02_test.go | 11 +++++++++++ day02/main.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/day02/day02_test.go b/day02/day02_test.go index 009ab8c..3528e6c 100644 --- a/day02/day02_test.go +++ b/day02/day02_test.go @@ -12,3 +12,14 @@ func Test1(t *testing.T) { t.Errorf("wrong result, expected %d, got %d", 150, res) } } + +func Test2(t *testing.T) { + res, err := calc2("../data/day02_test.dat") + if err != nil { + t.Errorf("error calculating: %v", err) + } + + if res != 900 { + t.Errorf("wrong result, expected %d, got %d", 150, res) + } +} diff --git a/day02/main.go b/day02/main.go index 6a2eadf..ec32804 100644 --- a/day02/main.go +++ b/day02/main.go @@ -14,6 +14,13 @@ func Run() { } fmt.Printf("Part 1: %d\n", res) + + res, err = calc2("data/day02.dat") + if err != nil { + log.Fatal(err) + } + + fmt.Printf("Part 2: %d\n", res) } func calc1(path string) (int, error) { @@ -43,3 +50,32 @@ func calc1(path string) (int, error) { return depth * hor, nil } + +func calc2(path string) (int, error) { + lines, err := readFile(path) + if err != nil { + return 0, err + } + + var hor, depth, aim int + for i := 0; i < len(lines); i++ { + v, err := strconv.Atoi(lines[i][1]) + if err != nil { + return 0, err + } + + switch lines[i][0] { + case "forward": + hor += v + depth += aim * v + case "down": + aim += v + case "up": + aim -= v + default: + return 0, errors.New("illegal direction command") + } + } + + return depth * hor, nil +} -- 2.44.0