2025-01-07 17:22:28 +00:00
|
|
|
package two
|
2024-12-05 18:24:22 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"io"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
|
2024-12-09 01:05:54 +00:00
|
|
|
"github.com/onyx-and-iris/aoc2024/day-05/internal/update"
|
|
|
|
)
|
2024-12-05 18:24:22 +00:00
|
|
|
|
2025-01-07 17:22:28 +00:00
|
|
|
func parseLines(r io.Reader) ([]update.Update, map[int][]int, error) {
|
2024-12-09 01:05:54 +00:00
|
|
|
var updates []update.Update
|
|
|
|
orderings := make(map[int][]int, 0)
|
|
|
|
|
|
|
|
var inUpdates bool
|
|
|
|
scanner := bufio.NewScanner(r)
|
|
|
|
for scanner.Scan() {
|
|
|
|
line := scanner.Text()
|
|
|
|
if len(line) == 0 {
|
|
|
|
inUpdates = true
|
|
|
|
continue
|
|
|
|
}
|
2024-12-05 18:24:22 +00:00
|
|
|
|
2024-12-09 01:05:54 +00:00
|
|
|
if inUpdates {
|
|
|
|
var update update.Update
|
|
|
|
for _, n := range strings.Split(line, ",") {
|
|
|
|
update.Pages = append(update.Pages, mustConv(n))
|
2024-12-05 18:24:22 +00:00
|
|
|
}
|
2024-12-09 01:05:54 +00:00
|
|
|
updates = append(updates, update)
|
|
|
|
} else {
|
|
|
|
left, right := func() (int, int) {
|
|
|
|
x := strings.Split(line, "|")
|
|
|
|
return mustConv(x[0]), mustConv(x[1])
|
|
|
|
}()
|
|
|
|
orderings[left] = append(orderings[left], right)
|
2024-12-05 18:24:22 +00:00
|
|
|
}
|
2024-12-09 01:05:54 +00:00
|
|
|
}
|
2024-12-05 18:24:22 +00:00
|
|
|
|
2024-12-09 01:05:54 +00:00
|
|
|
if err := scanner.Err(); err != nil {
|
|
|
|
return nil, nil, err
|
2024-12-05 18:24:22 +00:00
|
|
|
}
|
|
|
|
|
2024-12-09 01:05:54 +00:00
|
|
|
return updates, orderings, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func mustConv(s string) int {
|
|
|
|
n, err := strconv.Atoi(s)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return n
|
2024-12-05 18:24:22 +00:00
|
|
|
}
|