[2020-12-02] Add solutions for day02

master
Elis Hirwing 2020-12-01 06:27:43 +01:00
parent 9e034e4eae
commit e0674428d0
Signed by: etu
GPG Key ID: D57EFA625C9A925F
7 changed files with 1101 additions and 0 deletions

View File

@ -6,6 +6,8 @@ day01:
go run main.go day01 input
day02:
go run main.go day02 input
day03:
day04:
day05:

3
day02/example.txt Normal file
View File

@ -0,0 +1,3 @@
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc

1000
day02/input.txt Normal file

File diff suppressed because it is too large Load Diff

50
day02/parse.go Normal file
View File

@ -0,0 +1,50 @@
package day02
import (
"log"
"regexp"
"strconv"
"git.elis.nu/etu/aoc2020/utils"
)
type PasswordPolicy struct {
LowerIndex int
HigherIndex int
ValidationChar byte
Password string
}
var rows []PasswordPolicy
func ParseFile(input string) {
// Parse file
for _, line := range utils.GetLinesFromFile("day02/" + input + ".txt") {
re := regexp.MustCompile(`(\d+)-(\d+) (\w+): (\w+)`)
// Match line against regex
matches := re.FindStringSubmatch(line)
// Parse ints
index1, err1 := strconv.Atoi(string(matches[1]))
index2, err2 := strconv.Atoi(string(matches[2]))
if err1 != nil {
log.Println("Failed to parse entry", err1)
continue
}
if err2 != nil {
log.Println("Failed to parse entry", err2)
continue
}
// Store password policy in list
rows = append(rows, PasswordPolicy{
LowerIndex: index1,
HigherIndex: index2,
ValidationChar: matches[3][0],
Password: string(matches[4]),
})
}
}

20
day02/solve1.go Normal file
View File

@ -0,0 +1,20 @@
package day02
import (
"log"
"strings"
)
func Solve1() {
counter := 0
for _, row := range rows {
occurances := strings.Count(row.Password, string(row.ValidationChar))
if row.LowerIndex <= occurances && occurances <= row.HigherIndex {
counter++
}
}
log.Println("2020-12-02.01: Answer:", counter)
}

22
day02/solve2.go Normal file
View File

@ -0,0 +1,22 @@
package day02
import "log"
func Solve2() {
counter := 0
for _, row := range rows {
lowerChar := row.Password[row.LowerIndex-1]
higherChar := row.Password[row.HigherIndex-1]
if lowerChar == higherChar {
continue
}
if lowerChar == row.ValidationChar || higherChar == row.ValidationChar {
counter++
}
}
log.Println("2020-12-02.02: Answer:", counter)
}

View File

@ -5,6 +5,7 @@ import (
"os"
"git.elis.nu/etu/aoc2020/day01"
"git.elis.nu/etu/aoc2020/day02"
"git.elis.nu/etu/aoc2020/utils"
)
@ -16,5 +17,8 @@ func main() {
switch os.Args[1] {
case "day01":
utils.Perf("2020-12-01", day01.ParseFile, day01.Solve1, day01.Solve2)
case "day02":
utils.Perf("2020-12-02", day02.ParseFile, day02.Solve1, day02.Solve2)
}
}