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