-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday09.go
86 lines (68 loc) · 1.8 KB
/
day09.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"slices"
"github.com/julijane/advent-of-code-2024/aoc"
)
type FileBlocks struct {
FileID int
Pos int
Length int
}
func defrag(files []FileBlocks, gaps []FileBlocks) int {
for i := len(files) - 1; i >= 0; i-- {
if len(gaps) == 0 {
break
}
for j, gap := range gaps {
if gap.Pos > files[i].Pos {
break
}
if gap.Length >= files[i].Length {
files[i].Pos = gap.Pos
if gap.Length > files[i].Length {
gaps[j].Pos += files[i].Length
gaps[j].Length -= files[i].Length
} else {
gaps = append(gaps[:j], gaps[j+1:]...)
}
break
}
}
}
sum := 0
for _, file := range files {
for pos := file.Pos; pos < file.Pos+file.Length; pos++ {
sum += pos * file.FileID
}
}
return sum
}
func calc(input *aoc.Input, _, _ bool, _ ...any) (any, any) {
line := input.PlainLines()[0]
gapsPart2 := []FileBlocks{}
filesPart2 := []FileBlocks{}
for fileid, pos, i := 0, 0, 0; i < len(line); i, fileid = i+2, fileid+1 {
lengthFile := int(line[i] - '0')
filesPart2 = append(filesPart2, FileBlocks{FileID: fileid, Pos: pos, Length: lengthFile})
pos += lengthFile
if i < len(line)-1 {
lengthGap := int(line[i+1] - '0')
gapsPart2 = append(gapsPart2, FileBlocks{FileID: -1, Pos: pos, Length: lengthGap})
pos += lengthGap
}
}
// Part 1 is just a special case of Part 2 where we split the files into blocks of just 1 length
filesPart1 := []FileBlocks{}
gapsPart1 := slices.Clone(gapsPart2)
for _, file := range filesPart2 {
for j := 0; j < file.Length; j++ {
filesPart1 = append(filesPart1, FileBlocks{FileID: file.FileID, Pos: file.Pos + j, Length: 1})
}
}
//
return defrag(filesPart1, gapsPart1), defrag(filesPart2, gapsPart2)
}
func main() {
aoc.Run("sample1.txt", calc, true, true)
aoc.Run("input.txt", calc, true, true)
}