2024-12-10 21:42:26 +00:00
|
|
|
package two
|
|
|
|
|
|
|
|
import (
|
2024-12-19 12:54:40 +00:00
|
|
|
"bufio"
|
2024-12-10 21:42:26 +00:00
|
|
|
"bytes"
|
2024-12-19 12:54:40 +00:00
|
|
|
"io"
|
|
|
|
"slices"
|
|
|
|
"strconv"
|
2024-12-10 21:42:26 +00:00
|
|
|
)
|
|
|
|
|
2024-12-19 12:54:40 +00:00
|
|
|
const empty = -1
|
|
|
|
|
2024-12-10 21:42:26 +00:00
|
|
|
func Solve(buf []byte) (int, error) {
|
|
|
|
r := bytes.NewReader(buf)
|
2024-12-19 12:54:40 +00:00
|
|
|
expandedRaw, err := parseLines(r)
|
2024-12-10 21:42:26 +00:00
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
2024-12-19 12:54:40 +00:00
|
|
|
disk := newDisk(expandedRaw)
|
|
|
|
disk.defragment()
|
|
|
|
disk.write()
|
2024-12-10 21:42:26 +00:00
|
|
|
|
2024-12-19 12:54:40 +00:00
|
|
|
var sum int
|
|
|
|
for i, n := range disk.data {
|
|
|
|
if n == empty {
|
2024-12-10 21:42:26 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2024-12-19 12:54:40 +00:00
|
|
|
sum += i * n
|
2024-12-10 21:42:26 +00:00
|
|
|
}
|
|
|
|
|
2024-12-19 12:54:40 +00:00
|
|
|
return sum, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseLines(r io.Reader) ([]int, error) {
|
|
|
|
var line string
|
|
|
|
scanner := bufio.NewScanner(r)
|
|
|
|
for scanner.Scan() {
|
|
|
|
line = scanner.Text()
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
raw := [][]int{}
|
|
|
|
for i, id := 0, 0; i < len(line); i, id = i+2, id+1 {
|
|
|
|
raw = append(raw, []int{id, mustConv(string(line[i]))})
|
|
|
|
var free int
|
|
|
|
if i < len(line)-1 {
|
|
|
|
free = mustConv(string(line[i+1]))
|
|
|
|
}
|
|
|
|
raw = append(raw, []int{empty, free})
|
|
|
|
}
|
|
|
|
|
|
|
|
expandedRaw := []int{}
|
|
|
|
for _, vals := range raw {
|
|
|
|
segment := slices.Repeat([]int{vals[0]}, vals[1])
|
|
|
|
expandedRaw = append(expandedRaw, segment...)
|
|
|
|
}
|
|
|
|
|
|
|
|
return expandedRaw, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func mustConv(s string) int {
|
|
|
|
n, err := strconv.Atoi(s)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return n
|
2024-12-10 21:42:26 +00:00
|
|
|
}
|