Advent of Code 2020: Day 05 with Python

meseta

Yuan Gao

Posted on December 6, 2020

Advent of Code 2020: Day 05 with Python

I'm going to keep this one short as I've run out of ways to make this interesting. Posting this for completeness.

The Challenge Part 1

Link to challenge on Advent of Code 2020 website

The challenge talks about a weird seating index scheme that uses binary partitioning. However, fancy words aside, they are literally talking about using binary.

One of the examples given was:

BFFFBBFRRR: row 70, column 7, seat ID 567
Enter fullscreen mode Exit fullscreen mode

ignoring the superfluous information about rows and columns (which don't appear anywhere in the challenge), we just need to know how to convert BFFFBBFRRR into the number 567.

The only solution, really.

Basically it's binary. if you replace all the B and R with 1, and the F and L with 0, then BFFFBBFRRR turns into 1000110111 which is 567 in binary.

We can do the converting into binary using some simple replace() functions, and then we can turn the ascii string into binary using python's existing int(value, 2) function. The second argument being the base system.

So, quite simply:

int(entry.replace("B", "1").replace("F", "0").replace("R", "1").replace("L", "0"), 2)
Enter fullscreen mode Exit fullscreen mode

Will give you the seat number from any given string. We can quickly scan the input data using this and list comprehension:

seats = [int(entry.replace("B", "1").replace("F", "0").replace("R", "1").replace("L", "0"), 2) for entry in open("input.txt").readlines()]
Enter fullscreen mode Exit fullscreen mode

The first part of the question asks for the highest seat number in the list. We simply have to do max(seats) to find out

print("highest seat", max(seats))
Enter fullscreen mode Exit fullscreen mode

The Challenge Part 2

The second part of the question says that there is a missing seat somewhere in the middle, but to also ignore the missing seats at either end of the range. We can use set comprehension again for this:

print("my seat", set(range(min(seats), max(seats))).difference(seats))
Enter fullscreen mode Exit fullscreen mode

Tadaa!
Onwards!

💖 💪 🙅 🚩
meseta
Yuan Gao

Posted on December 6, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Advent of Code 2023 - December 16th
advent Advent of Code 2023 - December 16th

December 18, 2023

Advent of Code 2023 - December 15th
advent Advent of Code 2023 - December 15th

December 15, 2023

Advent of Code 2023 - December 13th
advent Advent of Code 2023 - December 13th

December 13, 2023

Advent of Code 2023 - December 8th
advent Advent of Code 2023 - December 8th

December 8, 2023

Advent of Code 2023 - December 7th
advent Advent of Code 2023 - December 7th

December 7, 2023