From 785a00400fee32ada5bbb9fb430a25d71dd65123 Mon Sep 17 00:00:00 2001 From: Gregory Date: Tue, 8 Feb 2022 20:32:54 +0200 Subject: [PATCH] day 1 part 2 --- .gitignore | 3 ++- client/client.go | 4 ++-- d1/d1.go | 21 +++++++++++++++++++++ d1/d1_test.go | 17 +++++++++++++++++ main.go | 18 +++++++++++------- 5 files changed, 53 insertions(+), 10 deletions(-) diff --git a/.gitignore b/.gitignore index 600d2d3..2db3e61 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -.vscode \ No newline at end of file +.vscode +session \ No newline at end of file diff --git a/client/client.go b/client/client.go index c28f682..96812d0 100644 --- a/client/client.go +++ b/client/client.go @@ -15,7 +15,7 @@ func NewClient(session string) client { return client{session} } -func (c *client) Day(day int) []byte { +func (c *client) Day(day int) string { client := http.Client{} req, err := http.NewRequest("GET", fmt.Sprintf("https://adventofcode.com/2021/day/%v/input", day), nil) @@ -37,5 +37,5 @@ func (c *client) Day(day int) []byte { log.Fatalln(err) } - return body + return string(body) } diff --git a/d1/d1.go b/d1/d1.go index 7f7c853..c7e1311 100644 --- a/d1/d1.go +++ b/d1/d1.go @@ -20,3 +20,24 @@ func D1(scans string) int64 { return int64(downs) } + +func D1P2(scans string) int64 { + depths := strings.Split(strings.TrimSpace(scans), "\n") + downs := 0 + + for i := 3; i < len(depths); i++ { + fourth, _ := strconv.Atoi(strings.TrimSpace(depths[i])) + third, _ := strconv.Atoi(strings.TrimSpace(depths[i-1])) + second, _ := strconv.Atoi(strings.TrimSpace(depths[i-2])) + first, _ := strconv.Atoi(strings.TrimSpace(depths[i-3])) + + prev := first + second + third + next := second + third + fourth + + if next > prev { + downs++ + } + } + + return int64(downs) +} diff --git a/d1/d1_test.go b/d1/d1_test.go index c82a894..e59682c 100644 --- a/d1/d1_test.go +++ b/d1/d1_test.go @@ -23,3 +23,20 @@ func TestD1(t *testing.T) { assert.EqualValues(t, 7, actual) } + +func TestD1P2(t *testing.T) { + input := ` + 199 + 200 + 208 + 210 + 200 + 207 + 240 + 269 + 260 + 263 + ` + + assert.EqualValues(t, 5, D1P2(input)) +} diff --git a/main.go b/main.go index 0fd0c68..aaab4c2 100644 --- a/main.go +++ b/main.go @@ -1,8 +1,8 @@ package main import ( - "bufio" "fmt" + "log" "os" "strings" @@ -13,11 +13,15 @@ import ( func main() { - reader := bufio.NewReader(os.Stdin) - fmt.Print("Enter your session: ") - session, _ := reader.ReadString('\n') - client := client.NewClient(strings.TrimSpace(session)) + session, err := os.ReadFile("session") - fmt.Printf("day1: %v\n", d1.D1(string(client.Day(1)))) - fmt.Printf("day2: %v\n", d2.D2(string(client.Day(2)))) + if err != nil { + log.Fatal(err) + } + + client := client.NewClient(strings.TrimSpace(string(session))) + + fmt.Printf("day 1: %v\n", d1.D1(client.Day(1))) + fmt.Printf("day 1 part 2: %v\n", d1.D1P2(client.Day(1))) + fmt.Printf("day 2: %v\n", d2.D2(client.Day(2))) }