From d40296e9834fffce72e8312a8ac625d742cb94d8 Mon Sep 17 00:00:00 2001 From: Daniel Lin Date: Mon, 4 Dec 2023 01:47:40 -0500 Subject: [PATCH] Day 4: Scratchcards --- README.md | 2 +- py/aoc2023/day4.py | 47 ++++++++++++++++++++++++++++++++++++++++++++++ py/pyproject.toml | 1 + 3 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 py/aoc2023/day4.py diff --git a/README.md b/README.md index d937725f..57c69bc3 100644 --- a/README.md +++ b/README.md @@ -8,4 +8,4 @@ Development occurs in language-specific directories: |[Day1.hs](hs/src/Day1.hs)|[Day1.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day1.kt)|[day1.py](py/aoc2023/day1.py)|[day1.rs](rs/src/day1.rs)| |[Day2.hs](hs/src/Day2.hs)|[Day2.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day2.kt)|[day2.py](py/aoc2023/day2.py)|[day2.rs](rs/src/day2.rs)| |[Day3.hs](hs/src/Day3.hs)|[Day3.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day3.kt)|[day3.py](py/aoc2023/day3.py)|[day3.rs](rs/src/day3.rs)| -|[Day4.hs](hs/src/Day4.hs)|[Day4.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day4.kt)||| +|[Day4.hs](hs/src/Day4.hs)|[Day4.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day4.kt)|[day4.py](py/aoc2023/day4.py)|| diff --git a/py/aoc2023/day4.py b/py/aoc2023/day4.py new file mode 100644 index 00000000..3b933a22 --- /dev/null +++ b/py/aoc2023/day4.py @@ -0,0 +1,47 @@ +""" +Day 4: Scratchcards +""" + +SAMPLE_INPUT = """ +Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 +Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 +Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 +Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 +Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 +Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11 +""" + + +def _parse(data): + for line in data.splitlines(): + if not line: + continue + line = line[line.index(":") + 1 :] + left, right = line.split("|", maxsplit=1) + left = set(left.split()) + right = set(right.split()) + yield len(left & right) + + +def part1(data): + """ + >>> part1(SAMPLE_INPUT) + 13 + """ + return sum(1 << card >> 1 for card in _parse(data)) + + +def part2(data): + """ + >>> part2(SAMPLE_INPUT) + 30 + """ + cards = list(_parse(data)) + counts = [1 for _ in cards] + for i, card in enumerate(cards): + for j in range(card): + counts[i + j + 1] += counts[i] + return sum(counts) + + +parts = (part1, part2) diff --git a/py/pyproject.toml b/py/pyproject.toml index 778e9112..267ccf64 100644 --- a/py/pyproject.toml +++ b/py/pyproject.toml @@ -25,6 +25,7 @@ aoc2023 = "aoc2023.main:main" day1 = "aoc2023.day1:parts" day2 = "aoc2023.day2:parts" day3 = "aoc2023.day3:parts" +day4 = "aoc2023.day4:parts" [tool.black] target_version = ["py312"]