Skip to content
This repository has been archived by the owner on Dec 25, 2024. It is now read-only.

Commit

Permalink
slight optimization to day 9 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
asottile committed Dec 14, 2024
1 parent d36081d commit e4e2555
Showing 1 changed file with 9 additions and 5 deletions.
14 changes: 9 additions & 5 deletions day09/part2.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,15 @@ def compute(s: str) -> int:
disk.append(File(did, n1))
disk.append(Free(n2))

searchfrom = len(disk) - 1

def _pos(did: int) -> tuple[int, File]:
for i, segment in enumerate(reversed(disk)):
if isinstance(segment, File) and segment.did == did:
return len(disk) - i - 1, segment
else:
raise AssertionError('unreachable!')
nonlocal searchfrom
segment = disk[searchfrom]
while not isinstance(segment, File) or segment.did != did:
searchfrom -= 1
segment = disk[searchfrom]
return searchfrom, segment

def _target(*, size: int, maxpos: int) -> tuple[int, Free] | None:
for i in range(maxpos):
Expand All @@ -62,6 +65,7 @@ def _target(*, size: int, maxpos: int) -> tuple[int, Free] | None:
disk[pos] = Free(segment.size)
disk[target_pos] = Free(target_free.size - segment.size)
disk.insert(target_pos, segment)
searchfrom += 1

total = 0
offset = 0
Expand Down

0 comments on commit e4e2555

Please sign in to comment.