advent-of-code 8 min read

[Day 4] Scratchcards // Advent of Code 2023 (Python)

Solving Advent of Code 2023 Day 4 in Python: scoring scratchcards with 2^(n-1) points, then tracking won copies with a card count repository for Part 2.

Scratchcards (via DALL-E 3)

Scratchcards (via DALL-E 3)

Advent of Code
The gondola takes you up. Strangely, though, the ground doesn’t seem to be coming with you; you’re not climbing a…adventofcode.com

Part One

The gondola takes you up. Strangely, though, the ground doesn’t seem to be coming with you; you’re not climbing a mountain. As the circle of Snow Island recedes below you, an entire new landmass suddenly appears above you! The gondola carries you to the surface of the new island and lurches into the station.

As you exit the gondola, the first thing you notice is that the air here is much warmer than it was on Snow Island. It’s also quite humid. Is this where the water source is?

The next thing you notice is an Elf sitting on the floor across the station in what seems to be a pile of colorful square cards.

“Oh! Hello!” The Elf excitedly runs over to you. “How may I be of service?” You ask about water sources.

“I’m not sure; I just operate the gondola lift. That does sound like something we’d have, though — this is Island Island, after all! I bet the gardener would know. He’s on a different island, though — er, the small kind surrounded by water, not the floating kind. We really need to come up with a better naming scheme. Tell you what: if you can help me with something quick, I’ll let you borrow my boat and you can go visit the gardener. I got all these scratchcards as a gift, but I can’t figure out what I’ve won.”

The Elf leads you over to the pile of colorful cards. There, you discover dozens of scratchcards, all with their opaque covering already scratched off. Picking one up, it looks like each card has two lists of numbers separated by a vertical bar (|): a list of winning numbers and then a list of numbers you have. You organize the information into a table (your puzzle input).

As far as the Elf has been able to figure out, you have to figure out which of the numbers you have appear in the list of winning numbers. The first match makes the card worth one point and each match after the first doubles the point value of that card.

For example:

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

In the above example, card 1 has five winning numbers (41, 48, 83, 86, and 17) and eight numbers you have (83, 86, 6, 31, 17, 9, 48, and 53). Of the numbers you have, four of them (48, 83, 17, and 86) are winning numbers! That means card 1 is worth 8 points (1 for the first match, then doubled three times for each of the three matches after the first).

  • Card 2 has two winning numbers (32 and 61), so it is worth 2 points.
  • Card 3 has two winning numbers (1 and 21), so it is worth 2 points.
  • Card 4 has one winning number (84), so it is worth 1 point.
  • Card 5 has no winning numbers, so it is worth no points.
  • Card 6 has no winning numbers, so it is worth no points.

So, in this example, the Elf’s pile of scratchcards is worth 13 points.

Take a seat in the large pile of colorful cards. How many points are they worth in total?


💭 Reading the problem, it is clear that we need to process each gamecard independently, get it’s points, and then find a total sum of all the points of all the gamecards.

This allows us to break down the problem, so we can focus on just 1 gamecard first and then extrapolate our solution to the whole list.

So, first things first, let’s write down the base test case provided to us in the puzzle:

TDD for the win! 👊

TDD for the win! 👊

So, ofcourse when we run this, we get:

❯ /Users/jmalik/.pyenv/versions/3.11.0rc2/bin/python /Users/jmalik/github/advent-of-code-2023/day_4/scratchcards.py
Traceback (most recent call last):
  File "/Users/jmalik/github/advent-of-code-2023/day_4/scratchcards.py", line 17, in <module>
    test_calculate_total_points()
  File "/Users/jmalik/github/advent-of-code-2023/day_4/scratchcards.py", line 13, in test_calculate_total_points
    assert total_points == 13, f"Expected 13, got {total_points}"
AssertionError: Expected 13, got None

Let’s now try to look into how we can calculate the points for a scratchcards. If we look into the example, we can see that an ideal scratchcard looks like:

Card 1: 41 48 83 86 17 | 83 86  6 31 17  9 48 53

where, it’s Card Number, followed by Winning numbers seprated by a whitespace each and then following by Your numbers and they both are seprated by a pipe | .

Quickly whipping your a terminal window with ipython3 we can do basically data sanity using our beloved split() function:

We can also observe, that we calculate points by “doubling” 1, n numbers of times, where n is the count of winning numbers in a scratchcard.

1 → 2 → 4 → 8 ….

Does ⬆️ look familar? Yep! This seems to be growing at 2^(n-1)

My notes! I like to write as I think.

My notes! I like to write as I think.

So, putting this all together, the basic algo I can think of is:

  1. For each scratch card, match each number from your_numbers against winning_numbers and take a count of matches
  2. Calcualte value of that scratch card using 2^(n-1)
  3. Repeat 1–2 for each card, and do a total_value += card_value
  4. return total_value
  5. ???
  6. Profit!

Let’s convert this into simple POC code:

💡 Edge case: In case no match is found, we have to return 0 as 2**(n-1) will return 1 as n^0 == 1 is always true.

And, let’s run for the base test case…. 🤞

❯ /Users/jmalik/.pyenv/versions/3.11.0rc2/bin/python /Users/jmalik/github/advent-of-code-2023/day_4/scratchcards.py
All tests passed!

Noice! Now, let’s load up our puzzle input and pass it to our calculate_total_points() function:

And time for the ultimate run!

🥁

Woah! That was easy. First try!!! 🕶

Woah! That was easy. First try!!! 🕶

Let’s make our code a bit pythonic, shall we?

# --- Day 4: Scratchcards ---

class ScratchCardProcessor:
    def calculate_total_points(self, scratchcards):
        return sum(self._calculate_points(scratchcard) for scratchcard in scratchcards.splitlines())

    def _calculate_points(self, scratchcard):
        _, numbers = scratchcard.split(": ")
        winning_numbers, your_numbers = map(lambda ns: [int(n) for n in ns.split()], numbers.split(" | "))
        match_count = sum(1 for number in your_numbers if number in winning_numbers)

        return 0 if match_count == 0 else 2**(match_count - 1)

def part_1():
    processor = ScratchCardProcessor()
    with open("day_4/input.txt") as f:
        scratchcards = f.read()
    print(f"Total points: {processor.calculate_total_points(scratchcards)}")

if __name__ == "__main__":
    part_1()

Part Two

Just as you’re about to report your findings to the Elf, one of you realizes that the rules have actually been printed on the back of every card this whole time.

There’s no such thing as “points”. Instead, scratchcards only cause you to win more scratchcards equal to the number of winning numbers you have.

Specifically, you win copies of the scratchcards below the winning card equal to the number of matches. So, if card 10 were to have 5 matching numbers, you would win one copy each of cards 11, 12, 13, 14, and 15.

Copies of scratchcards are scored like normal scratchcards and have the same card number as the card they copied. So, if you win a copy of card 10 and it has 5 matching numbers, it would then win a copy of the same cards that the original card 10 won: cards 11, 12, 13, 14, and 15. This process repeats until none of the copies cause you to win any more cards. (Cards will never make you copy a card past the end of the table.)

This time, the above example goes differently:

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
  • Card 1 has four matching numbers, so you win one copy each of the next four cards: cards 2, 3, 4, and 5.
  • Your original card 2 has two matching numbers, so you win one copy each of cards 3 and 4.
  • Your copy of card 2 also wins one copy each of cards 3 and 4.
  • Your four instances of card 3 (one original and three copies) have two matching numbers, so you win four copies each of cards 4 and 5.
  • Your eight instances of card 4 (one original and seven copies) have one matching number, so you win eight copies of card 5.
  • Your fourteen instances of card 5 (one original and thirteen copies) have no matching numbers and win no more cards.
  • Your one instance of card 6 (one original) has no matching numbers and wins no more cards.

Once all of the originals and copies have been processed, you end up with 1instance of card 1, 2 instances of card 2, 4 instances of card 3, 8instances of card 4, 14 instances of card 5, and 1 instance of card 6. In total, this example pile of scratchcards causes you to ultimately have 30scratchcards!

Process all of the original and copied scratchcards until no more scratchcards are won. Including the original set of scratchcards, how many total scratchcards do you end up with?


Wait! WTF is this! 🤯

I had to re-read this problem a few times to make any sense of it. I picked up the pen and drew the expansion of tickets to get a visual cue about the function and I came up with:

Part 2 was quite puzzling TBH

Part 2 was quite puzzling TBH

💭 Once, I had this visually in front of me, it all started to make some sense. All we had to do is maintain 2 datapoints for each ticket:

  1. Count of match with winning numbers (static)
  2. Number of duplicate scratchcards (dynamic as number of dups will grow as we process predecessor scratchcards!)

And at the end of processing all cards, all we had to calcualte is the sum(number_of_cards) where number_of_cards = count(original + duplicates) .

First, let’s write our base test case as given in example in the puzzle!

💡This is always a good thing if you are given any test cases as it helps you play around and identify any potential edge cases!

And now calling it, we should see a failure! 🔴

❯ /Users/jmalik/.pyenv/versions/3.11.0rc2/bin/python /Users/jmalik/github/advent-of-code-2023/day_4/scratchcards.py
test_calculate_total_points passed!
Total points: 25571
Traceback (most recent call last):
  File "/Users/jmalik/github/advent-of-code-2023/day_4/scratchcards.py", line 55, in <module>
    ScratchCardProcessor.test_calculate_total_scratchcards()
  File "/Users/jmalik/github/advent-of-code-2023/day_4/scratchcards.py", line 42, in test_calculate_total_scratchcards
    assert total_scratchcards == 30, f"Expected 30, got {total_scratchcards}"
AssertionError: Expected 30, got None

Yep, let’s write a POC code and see what we can come up with to fix this test case!

My idea was to not touch the input (original) scratchcard file and just maintain a simple repository at class level to just keep the dynamic count of number of scratchcards! So, I just introduced that and initiated it with card_id: 1 for all card_ids present in the input! Something like:

And then using this one, I could just get the count_match and then run a loop to do a +1 against successive card_ids . The idea was pretty neat and clean allowing me to also reuse a part of old code logic from part 1.

This wasn’t smooth sailing, but after fixing a couple of bugs and debugging it line by line for the base test case, we were able to match the state of repository with our notebook:

Repository with card_id:count looks promising!

Repository with card_id:count looks promising!

And….voila! Our base test case is now green! 🟢

❯  cd /Users/jmalik/github/advent-of-code-2023 ; /usr/bin/env /Users/jmalik/.pyenv/versions/3.11.0rc2/bin/python /Users/jmalik/.vscode/extensions/ms-python.python-2023.20.0/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 58812 -- /Users/jmalik/github/advent-of-code-2023/day_4/scratchcards.py
test_calculate_total_points passed!
Total points: 25571
test_calculate_total_scratchcards passed!

Let’s now just write a simple function part_2() to load up the input.txt and run it for our new function calculate_total_scratchcards() ?

And surely, our code compiles beautifully and we get a number — xxx .

Let’s put this into the answer box at the website….and…..

Booom!

Booom!

Here’s the final pythonic code, with docstrings, list comprehentions and yada yada…I was feeling really happy to solve this with such precision! 🤌

# --- Day 4: Scratchcards ---

class ScratchCardProcessor:
    """Processes scratch cards to calculate total points and total scratchcards."""
    
    def __init__(self, scratchcards: str):
        """Initializes the processor with a string of scratchcards."""
        self.scratchcards = scratchcards
        self.repository = {self._get_card_id(scratchcard): 1 for scratchcard in self._get_lines()}

    def calculate_total_points(self) -> int:
        """Calculates the total points from all scratchcards."""
        return sum(self._calculate_points(scratchcard) for scratchcard in self._get_lines())
    
    def calculate_total_scratchcards(self) -> int:
        """Calculates the total number of scratchcards."""
        for scratchcard in self._get_lines():
            card_id = self._get_card_id(scratchcard)
            match_count = self._get_match_count(scratchcard)
            for i in range(1, match_count + 1):
                self.repository[card_id + i] += self.repository[card_id]
        
        return sum(self.repository.values())

    def _get_lines(self):
        """Splits the scratchcards string into individual lines."""
        return self.scratchcards.splitlines()

    def _get_card_id(self, scratchcard: str) -> int:
        """Extracts the card ID from a scratchcard string."""
        return int(scratchcard.split(":")[0].split()[1])

    def _get_match_count(self, scratchcard: str) -> int:
        """Calculates the match count for a scratchcard."""
        _, numbers = scratchcard.split(": ")
        winning_numbers, your_numbers = (set(map(int, ns.split())) for ns in numbers.split(" | "))
        return len(your_numbers & winning_numbers)

    def _calculate_points(self, scratchcard: str) -> int:
        """Calculates points for a single scratchcard."""
        match_count = self._get_match_count(scratchcard)
        return 0 if match_count == 0 else 2 ** (match_count - 1)

    @staticmethod
    def test_calculate_total_points():
        scratchcards = """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
"""
        processor = ScratchCardProcessor(scratchcards)
        total_points = processor.calculate_total_points()
        assert total_points == 13, f"Expected 13, got {total_points}"
        print("test_calculate_total_points passed!")

    @staticmethod
    def test_calculate_total_scratchcards():
        scratchcards = """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
"""
        processor = ScratchCardProcessor(scratchcards)
        total_scratchcards = processor.calculate_total_scratchcards()
        assert total_scratchcards == 30, f"Expected 30, got {total_scratchcards}"
        print("test_calculate_total_scratchcards passed!")

def part_1():
    with open("day_4/input.txt") as f:
        scratchcards = f.read()

    processor = ScratchCardProcessor(scratchcards)
    print(f"Total points: {processor.calculate_total_points()}")

def part_2():
    with open("day_4/input.txt") as f:
        scratchcards = f.read()

    processor = ScratchCardProcessor(scratchcards)
    print(f"Total scratchcards: {processor.calculate_total_scratchcards()}")

if __name__ == "__main__":
    ScratchCardProcessor.test_calculate_total_points()
    part_1()

    ScratchCardProcessor.test_calculate_total_scratchcards()
    part_2()

p.s: I am deliberating not adding answers here so you can actually spend some time trying to understand how we solved the problem!

Feel free to checkout code on my Github repo and try to set it up and run on your machine 👇

GitHub - jatinkrmalik/advent-of-code-2023: Advent of Code is an Advent calendar of small…
Advent of Code is an Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can…github.com

Leave a comment

Keep reading

advent-of-code 2 min

🎄Solve Advent of Code 2024 With Me!

Announcing a spoiler-free YouTube video series for Advent of Code 2024 that focuses on how to analyze and approach each puzzle, not just the answers.