Browse Source

complete day 5

master
Alexander Avery 2 weeks ago
parent
commit
95304d3d6d
  1. 99
      2024/day05.go
  2. 1373
      2024/inputs/05.txt
  3. 33
      2024/puzzle_test.go
  4. 1
      main.go

99
2024/day05.go

@ -0,0 +1,99 @@
package adventoc2024
import (
"bufio"
"io"
"slices"
"sort"
"strings"
)
type Day5 struct{}
func (d Day5) Part1(r io.Reader) string {
s := bufio.NewScanner(r)
before := make(map[int][]int, 100)
var sum int
var updates bool
Scan:
for s.Scan() {
updates = updates || s.Text() == ""
if !updates {
s1, s2, _ := strings.Cut(s.Text(), "|")
i, j := atoi(s1), atoi(s2)
before[j] = append(before[j], i)
} else if s.Text() != "" {
pages := strings.Split(s.Text(), ",")
var v1, v2 int
for i := range pages {
v1 = atoi(pages[i])
for j := range pages[i+1:] {
v2 = atoi(pages[i+j+1])
for _, mustbefore := range before[v1] {
if mustbefore == v2 {
continue Scan
}
}
}
}
sum += atoi(pages[(len(pages)-1)/2])
}
}
return printi(sum)
}
func (d Day5) Part2(r io.Reader) string {
s := bufio.NewScanner(r)
before := make(map[int][]int, 100)
var sum int
var updates bool
for s.Scan() {
updates = updates || s.Text() == ""
if !updates {
s1, s2, _ := strings.Cut(s.Text(), "|")
i, j := atoi(s1), atoi(s2)
before[j] = append(before[j], i)
} else if s.Text() != "" {
pages := strings.Split(s.Text(), ",")
pageNums := make([]int, len(pages))
pageCopy := make([]int, len(pages))
for i := range pages {
pageNums[i], pageCopy[i] = atoi(pages[i]), atoi(pages[i])
}
sortPages(pageNums, before)
if !slices.Equal(pageNums, pageCopy) {
sum += middlePage(pageNums)
}
}
}
return printi(sum)
}
func sortPages(update []int, before map[int][]int) {
sort.Slice(update, func(i, j int) bool {
v1 := update[i]
v2 := update[j]
search := before[v1]
for k := range search {
if search[k] == v2 {
return false
}
}
return true
})
}
func middlePage(pages []int) int {
return pages[(len(pages)-1)/2]
}

1373
2024/inputs/05.txt

File diff suppressed because it is too large

33
2024/puzzle_test.go

@ -80,6 +80,39 @@ S.S.S.S.S.
M.M.M.M.M. M.M.M.M.M.
..........`, ..........`,
}, },
{
solver: Day5{},
ans1: "143",
ans2: "123",
inp1: `47|53
97|13
97|61
97|47
75|29
61|13
75|53
29|13
97|29
53|29
61|53
97|53
61|29
47|13
75|47
97|75
47|61
75|61
47|29
75|13
53|13
75,47,61,53,29
97,61,53,29,13
75,29,13
75,97,47,61,53
61,13,29
97,13,75,29,47`,
},
} }
for i, tt := range tests { for i, tt := range tests {

1
main.go

@ -20,6 +20,7 @@ var puzzles = map[string]puzzle{
"2": adventoc2024.Day2{}, "2": adventoc2024.Day2{},
"3": adventoc2024.Day3{}, "3": adventoc2024.Day3{},
"4": adventoc2024.Day4{}, "4": adventoc2024.Day4{},
"5": adventoc2024.Day5{},
} }
func main() { func main() {

Loading…
Cancel
Save