Browse Source

[2020-12-02] Add solutions for day02

master
Elis Hirwing 10 months ago
parent
commit
e0674428d0
Signed by: etu GPG Key ID: D57EFA625C9A925F
  1. 2
      Makefile
  2. 3
      day02/example.txt
  3. 1000
      day02/input.txt
  4. 50
      day02/parse.go
  5. 20
      day02/solve1.go
  6. 22
      day02/solve2.go
  7. 4
      main.go

2
Makefile

@ -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

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

1000
day02/input.txt

File diff suppressed because it is too large

50
day02/parse.go

@ -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

@ -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

@ -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)
}

4
main.go

@ -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)
}
}

Loading…
Cancel
Save