From abc742e2ad8fc53b7ef5166ae0a41a89458966e9 Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Sat, 3 Jul 2021 14:15:11 +0200 Subject: [PATCH] Implement day 22 part 1 --- 2019/aoc2019/day22.py | 44 ++++++++++++++++++++++++++++++++++++++++ 2019/tests/test_day22.py | 43 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 2019/aoc2019/day22.py create mode 100644 2019/tests/test_day22.py diff --git a/2019/aoc2019/day22.py b/2019/aoc2019/day22.py new file mode 100644 index 0000000..fc54e39 --- /dev/null +++ b/2019/aoc2019/day22.py @@ -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") diff --git a/2019/tests/test_day22.py b/2019/tests/test_day22.py new file mode 100644 index 0000000..78866a7 --- /dev/null +++ b/2019/tests/test_day22.py @@ -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