From 44e82799b8b91c3e195be6c43a124701501b5c12 Mon Sep 17 00:00:00 2001 From: Gregory Date: Mon, 7 Feb 2022 22:00:52 +0200 Subject: [PATCH] day2 --- d2/d2.go | 42 ++++++++++++++++++++++++++++++++++++++++++ d2/d2_test.go | 20 ++++++++++++++++++++ main.go | 2 ++ 3 files changed, 64 insertions(+) create mode 100644 d2/d2.go create mode 100644 d2/d2_test.go diff --git a/d2/d2.go b/d2/d2.go new file mode 100644 index 0000000..e2849a6 --- /dev/null +++ b/d2/d2.go @@ -0,0 +1,42 @@ +package d2 + +import ( + "log" + "strconv" + "strings" +) + +type position struct { + x int64 + y int64 +} + +func D2(input string) int64 { + position := position{} + directions := strings.Split(strings.TrimSpace(input), "\n") + + for _, direction := range directions { + directionAndValue := strings.Split(strings.TrimSpace(direction), " ") + + if len(directionAndValue) != 2 { + log.Fatal("line has wrong number of elements: ", direction) + } + + value, err := strconv.Atoi(directionAndValue[1]) + + if err != nil { + log.Fatal(err) + } + + switch directionAndValue[0] { + case "forward": + position.x += int64(value) + case "down": + position.y += int64(value) + case "up": + position.y -= int64(value) + } + } + + return position.x * position.y +} diff --git a/d2/d2_test.go b/d2/d2_test.go new file mode 100644 index 0000000..2342fce --- /dev/null +++ b/d2/d2_test.go @@ -0,0 +1,20 @@ +package d2 + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestD2(t *testing.T) { + + input := ` +forward 5 +down 5 +forward 8 +up 3 +down 8 +forward 2` + + assert.EqualValues(t, 150, D2(input)) +} diff --git a/main.go b/main.go index ede3869..0fd0c68 100644 --- a/main.go +++ b/main.go @@ -8,6 +8,7 @@ import ( "github.com/fotonmoton/aoc2021/client" "github.com/fotonmoton/aoc2021/d1" + "github.com/fotonmoton/aoc2021/d2" ) func main() { @@ -18,4 +19,5 @@ func main() { client := client.NewClient(strings.TrimSpace(session)) fmt.Printf("day1: %v\n", d1.D1(string(client.Day(1)))) + fmt.Printf("day2: %v\n", d2.D2(string(client.Day(2)))) }