Implement day 22 part 1

This commit is contained in:
2021-07-03 14:15:11 +02:00
parent a43f260e1b
commit abc742e2ad
2 changed files with 87 additions and 0 deletions

44
2019/aoc2019/day22.py Normal file
View File

@@ -0,0 +1,44 @@
from typing import List, TextIO
def shuffle(instructions: List[str], deck_size: int) -> List[int]:
deck = list(range(0, deck_size))
for instruction in instructions:
if "new stack" in instruction:
deck = list(reversed(deck))
continue
parts = instruction.split(" ")
if parts[0] == "cut":
by = int(parts[1])
new_deck = deck[by:]
new_deck += deck[:by]
deck = new_deck
else:
increment = int(parts[3])
new_deck = list(range(0, deck_size))
target_index = 0
for card in deck:
new_deck[target_index] = card
target_index = (target_index + increment) % len(deck)
deck = new_deck
return deck
def part1(data: TextIO):
instructions = [line.strip() for line in data]
result = shuffle(instructions, 10007)
for i, card in enumerate(result):
if card == 2019:
return i
raise Exception("Did not find card")

43
2019/tests/test_day22.py Normal file
View File

@@ -0,0 +1,43 @@
import pytest
from aoc2019.day22 import shuffle
SAMPLE_INSTRUCTIONS = [
"""deal with increment 7
deal into new stack
deal into new stack""",
"""cut 6
deal with increment 7
deal into new stack""",
"""deal with increment 7
deal with increment 9
cut -2""",
"""deal into new stack
cut -2
deal with increment 7
cut 8
cut -4
deal with increment 7
cut 3
deal with increment 9
deal with increment 3
cut -1""",
]
CORRECT_SHUFFLES = [
"0 3 6 9 2 5 8 1 4 7",
"3 0 7 4 1 8 5 2 9 6",
"6 3 0 7 4 1 8 5 2 9",
"9 2 5 8 1 4 7 0 3 6",
]
@pytest.mark.parametrize('instructions,correct', zip(SAMPLE_INSTRUCTIONS, CORRECT_SHUFFLES))
def test_shuffle(instructions, correct):
instructions = [line.strip() for line in instructions.splitlines()]
correct = [int(i) for i in correct.split(" ")]
result = shuffle(instructions, 10)
assert result == correct