day05 - no extra list, better indices

This commit is contained in:
Stefan Harmuth 2022-12-05 08:11:17 +01:00
parent 258baebab8
commit b3b0cc8b36

View File

@ -16,23 +16,20 @@ class Day(AOCDay):
]
]
def get_stacks_and_moves(self) -> (list, list):
def get_stacks_and_moves(self) -> (dict, list):
i = self.getInput()
stacks = {}
for l, line in enumerate(i):
if not line:
ret = []
for k in sorted(stacks.keys()):
ret.append(stacks[k])
return ret, i[l+1:]
return stacks, i[l+1:]
this_stacks = (len(line) + 1) // 4
for stack_num in range(this_stacks):
crate = line[stack_num * 4 + 1]
if ord(crate) > 64:
if stack_num not in stacks:
stacks[stack_num] = []
stacks[stack_num].append(crate)
if stack_num + 1 not in stacks:
stacks[stack_num + 1] = []
stacks[stack_num + 1].append(crate)
def part1(self) -> Any:
stacks, moves = self.get_stacks_and_moves()
@ -40,25 +37,19 @@ class Day(AOCDay):
l = move.split(" ")
count, move_from, move_to = map(int, [l[1], l[3], l[5]])
for _ in range(count):
stacks[move_to - 1].insert(0, stacks[move_from - 1].pop(0))
stacks[move_to].insert(0, stacks[move_from].pop(0))
string = ""
for x in stacks:
string += x.pop(0)
return string
return "".join(stacks[x].pop(0) for x in sorted(stacks))
def part2(self) -> Any:
stacks, moves = self.get_stacks_and_moves()
for move in moves:
l = move.split(" ")
count, move_from, move_to = map(int, [l[1], l[3], l[5]])
stacks[move_to - 1] = stacks[move_from - 1][:count] + stacks[move_to - 1]
stacks[move_from - 1] = stacks[move_from - 1][count:]
stacks[move_to] = stacks[move_from][:count] + stacks[move_to]
stacks[move_from] = stacks[move_from][count:]
string = ""
for x in stacks:
string += x.pop(0)
return string
return "".join(stacks[x].pop(0) for x in sorted(stacks))
if __name__ == '__main__':