feat: add day 5 2024
This commit is contained in:
83
aoc2024/day05/main.go
Normal file
83
aoc2024/day05/main.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
_ "embed"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
aoc "go.sour.is/advent-of-code"
|
||||
)
|
||||
|
||||
// var log = aoc.Log
|
||||
|
||||
func main() { aoc.MustResult(aoc.Runner(run)) }
|
||||
|
||||
type result struct {
|
||||
valuePT1 int
|
||||
valuePT2 int
|
||||
}
|
||||
|
||||
func (r result) String() string { return fmt.Sprintf("%#v", r) }
|
||||
|
||||
func run(scan *bufio.Scanner) (*result, error) {
|
||||
|
||||
ordering := make(map[int]aoc.Set[int])
|
||||
var updates [][]int
|
||||
|
||||
for scan.Scan() {
|
||||
txt := scan.Text()
|
||||
|
||||
if txt == "" {
|
||||
break
|
||||
}
|
||||
|
||||
var key, val int
|
||||
_, err := fmt.Sscanf(txt, "%d|%d", &val, &key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := ordering[key]; !ok {
|
||||
ordering[key] = aoc.NewSet[int]()
|
||||
}
|
||||
s := ordering[key]
|
||||
s.Add(val)
|
||||
}
|
||||
|
||||
var sum int
|
||||
var sum2 int
|
||||
|
||||
outer:
|
||||
for scan.Scan() {
|
||||
txt := scan.Text()
|
||||
|
||||
arr := aoc.SliceMap(aoc.Atoi, strings.Split(txt, ",")...)
|
||||
|
||||
for i, v := range arr {
|
||||
m, ok := ordering[v]
|
||||
if (i > 0 && !ok) || !m.ContainsAll(arr[:i]...) {
|
||||
sort.SliceStable(arr, func(i, j int) bool {
|
||||
if a, ok := ordering[arr[i]]; ok && a.Has(arr[j]) {
|
||||
return true
|
||||
}
|
||||
|
||||
if b, ok := ordering[arr[j]]; ok && b.Has(arr[i]) {
|
||||
return false
|
||||
}
|
||||
|
||||
return false
|
||||
})
|
||||
|
||||
sum2 += arr[len(arr)/2]
|
||||
|
||||
continue outer
|
||||
}
|
||||
}
|
||||
|
||||
sum += arr[len(arr)/2]
|
||||
updates = append(updates, arr)
|
||||
}
|
||||
|
||||
return &result{sum, sum2}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user