-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpart2.go
118 lines (105 loc) · 2.02 KB
/
part2.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package day09
import (
"container/list"
"strconv"
"github.com/patrick22414/Advent-of-Code-2024/readinput"
)
type ListDisk struct{ ls *list.List }
func (d ListDisk) Push(f DiskFile) {
d.ls.PushBack(f)
}
const (
NotAllocated int = iota - 1
AllocatedByReplace
AllocatedByInsert
)
// Find a free space for `f` before the n-th element and insert into it
//
// Returns:
//
// - 1: if successful and list length grew by 1
//
// - 0: if successful but list length did not grow
//
// - -1: if unsuccessful
func (d ListDisk) AllocBefore(f DiskFile, before int) int {
e, i := d.ls.Front(), 0
for i < before && e != nil {
v := e.Value.(DiskFile)
if v.id != -1 || v.size < f.size {
i++
e = e.Next()
continue
}
d.ls.InsertBefore(f, e)
v.size -= f.size
if v.size == 0 {
d.ls.Remove(e)
return AllocatedByReplace
}
e.Value = v
return AllocatedByInsert
}
return NotAllocated
}
func (d ListDisk) String() string {
s := ""
e := d.ls.Front()
for e != nil {
f := e.Value.(DiskFile)
for range f.size {
if f.id == -1 {
s += "."
} else {
s += strconv.Itoa(f.id)
}
}
e = e.Next()
}
return s
}
func Part2() int {
disk := ListDisk{list.New()}
for line := range readinput.ReadInput("./input.txt") {
for i := 0; i < len(line); i += 2 {
if line[i] != '0' {
disk.Push(DiskFile{id: i / 2, size: int(line[i] - '0')})
}
if i+1 < len(line) && line[i+1] != '0' {
disk.Push(DiskFile{id: -1, size: int(line[i+1] - '0')})
}
}
}
b, j := disk.ls.Back(), disk.ls.Len()-1
for b != nil {
v := b.Value.(DiskFile)
if v.id == -1 {
j--
b = b.Prev()
continue
}
// fmt.Println(disk, j, v)
alloc := disk.AllocBefore(v, j)
if alloc >= 0 {
// alloc is successful
b.Value = DiskFile{id: -1, size: v.size}
}
if alloc <= 0 {
j--
}
b = b.Prev()
}
i, total := 0, 0
for e := disk.ls.Front(); e != nil; e = e.Next() {
v := e.Value.(DiskFile)
if v.id != -1 {
for range v.size {
total += i * v.id
i++
}
} else {
i += v.size
}
}
return total
}