Initial commit
This commit is contained in:
commit
97a4330bc0
110 changed files with 7006 additions and 0 deletions
55
2024/9/one.py
Normal file
55
2024/9/one.py
Normal file
|
@ -0,0 +1,55 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
|
||||
input_file = sys.argv[1]
|
||||
|
||||
with open(input_file) as fd:
|
||||
lines = [line.rstrip() for line in fd.readlines()]
|
||||
|
||||
line = lines[0]
|
||||
|
||||
disk: list[int | None] = list()
|
||||
|
||||
fileno = 0
|
||||
isfile = True
|
||||
for char in line:
|
||||
n = int(char)
|
||||
if isfile:
|
||||
disk += [fileno] * n
|
||||
fileno += 1
|
||||
else:
|
||||
disk += [None] * n
|
||||
isfile = not isfile
|
||||
|
||||
beg = 0
|
||||
end = len(disk) - 1
|
||||
|
||||
|
||||
def print_disk() -> None:
|
||||
return
|
||||
print("".join(str(c) if c is not None else "." for c in disk))
|
||||
|
||||
|
||||
print_disk()
|
||||
moving = False
|
||||
while beg < end:
|
||||
if moving:
|
||||
if disk[end] is not None:
|
||||
disk[beg] = disk[end]
|
||||
disk[end] = None
|
||||
moving = False
|
||||
print_disk()
|
||||
end -= 1
|
||||
else:
|
||||
if disk[beg] is None:
|
||||
moving = True
|
||||
else:
|
||||
beg += 1
|
||||
|
||||
checksum = 0
|
||||
for c, cid in enumerate(disk):
|
||||
if cid is not None:
|
||||
checksum += c * cid
|
||||
|
||||
print(checksum)
|
64
2024/9/two.py
Normal file
64
2024/9/two.py
Normal file
|
@ -0,0 +1,64 @@
|
|||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
|
||||
input_file = sys.argv[1]
|
||||
|
||||
with open(input_file) as fd:
|
||||
lines = [line.rstrip() for line in fd.readlines()]
|
||||
|
||||
line = lines[0]
|
||||
|
||||
disk: list[int | None] = list()
|
||||
# position, size
|
||||
index: list[tuple[int, int]] = list()
|
||||
|
||||
fileno = 0
|
||||
isfile = True
|
||||
for char in line:
|
||||
n = int(char)
|
||||
if isfile:
|
||||
index.append((len(disk), n))
|
||||
disk += [fileno] * n
|
||||
fileno += 1
|
||||
else:
|
||||
disk += [None] * n
|
||||
isfile = not isfile
|
||||
|
||||
beg = 0
|
||||
end = len(disk) - 1
|
||||
|
||||
|
||||
def print_disk() -> None:
|
||||
return
|
||||
print("".join(str(c) if c is not None else "." for c in disk))
|
||||
|
||||
|
||||
print_disk()
|
||||
|
||||
for pos, size in index[::-1]:
|
||||
hole_start = None
|
||||
for c, cid in enumerate(disk + [-1]):
|
||||
if c > pos + size:
|
||||
break
|
||||
if cid is None:
|
||||
if hole_start is None:
|
||||
hole_start = c
|
||||
else:
|
||||
if hole_start is not None:
|
||||
hole_size = c - hole_start
|
||||
if hole_size < size:
|
||||
hole_start = None
|
||||
continue
|
||||
for i in range(size):
|
||||
disk[hole_start + i] = disk[pos + i]
|
||||
disk[pos + i] = None
|
||||
print_disk()
|
||||
break
|
||||
|
||||
checksum = 0
|
||||
for c, cid in enumerate(disk):
|
||||
if cid is not None:
|
||||
checksum += c * cid
|
||||
|
||||
print(checksum)
|
Loading…
Add table
Add a link
Reference in a new issue