From a2cb6ff664d4cc826c3d659272fc51f42a8fa3ab Mon Sep 17 00:00:00 2001 From: Araozu Date: Sun, 25 Feb 2024 15:46:40 -0500 Subject: [PATCH] Day 2 part 2 --- solutions/day02.go | 41 +++++++++++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 4 deletions(-) diff --git a/solutions/day02.go b/solutions/day02.go index 08d5b79..c94432c 100644 --- a/solutions/day02.go +++ b/solutions/day02.go @@ -5,7 +5,7 @@ import ( "strings" ) -func checkPassword(input string) bool { +func passwordPolicy1(input string) bool { dashPosition := strings.Index(input, "-") spacePosition := strings.Index(input, " ") colonPosition := strings.Index(input, ":") @@ -47,7 +47,7 @@ func Day02Part01(isTest bool) int { correctPasswords := 0 for _, i := range values { - if checkPassword(i) { + if passwordPolicy1(i) { correctPasswords += 1 } } @@ -55,6 +55,39 @@ func Day02Part01(isTest bool) int { return correctPasswords } -func Day02Part02(isTest bool) int { - return -1 +func passwordPolicy2(input string) bool { + dashPosition := strings.Index(input, "-") + spacePosition := strings.Index(input, " ") + colonPosition := strings.Index(input, ":") + firstIdx, err := strconv.Atoi(input[:dashPosition]) + if err != nil { + panic("Error converting to int") + } + firstIdx -= 1 + secondIdx, err := strconv.Atoi(input[dashPosition+1 : spacePosition]) + if err != nil { + panic("Error converting to int") + } + secondIdx -= 1 + letter := input[spacePosition+1 : colonPosition] + rest := input[colonPosition+2:] + + firstIdxIsTrue := string(rest[firstIdx]) == letter + secondIdxIsTrue := string(rest[secondIdx]) == letter + + return (firstIdxIsTrue && !secondIdxIsTrue) || (!firstIdxIsTrue && secondIdxIsTrue) +} + +func Day02Part02(isTest bool) int { + input := ReadInput("02", isTest) + values := strings.Split(input, "\n") + correctPasswords := 0 + + for _, i := range values { + if passwordPolicy2(i) { + correctPasswords += 1 + } + } + + return correctPasswords }