Alexander Avery
2 weeks ago
4 changed files with 1506 additions and 0 deletions
@ -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] |
|||
} |
File diff suppressed because it is too large
Loading…
Reference in new issue