DEV Community


Advent of Code 2020: Python Solution Day 5

Passionate ML and Game Dev learner from Nepal who loves sharing what he knows via blogging.
Updated on ・2 min read

This is the 5th day of Advent of Code 2020 and this is more interesting than previous one. But I quickly was able to find the solution. I usually solve solution on next day because I am having hard time managing time. And it is nearly hour left for day 6.
As usual, I have saved text file as day5.txt on same directory as my notebook is and my solution notebook is available at this repository.

with open("day5.txt", "r") as fp:
    lines = fp.readlines()

lines = [line[:-1] for line in lines]


# find row, 
# 0 to 127 rows
# f means lower half (0-63)
# b means upper half (63-127)
# r upper half of column (4-7)
# l lower half of column (0-3)

seat_ids = []
for line in lines:
    #print(f"Current Text: {line}")
    # to get row, take first 7 chars
    r = line[:7]
    start = 0
    end = 127
    row, col = 0, 0
    for char in r:
        #print(f"Char: {char}")
        if char == "F":
            end = int((start+end+1)/2) - 1
        elif char == "B":
            start = int((start+end+1)/2)
        #print(f"Start: {start} End: {end}")
    row = start

    # to get col, take last 3 chars
    r = line[7:]
    start = 0
    end = 7
    for char in r:
        #print(f"Char: {char}")
        if char == "L":
            end = int((start+end+1)/2) - 1
        elif char == "R":
            start = int((start+end+1)/2)
        #print(f"Start: {start} End: {end}")
    col = start
    # seat ID: multiply the row by 8, then add the column
    sid = row*8 + col
    print(f"Row: {row} Column: {col} Seat ID:{sid}")

print(f"Solution 1: {max(seat_ids)}")
print(f"Solution 2: {[seat for seat in range(min(seat_ids), max(seat_ids)) if seat not in seat_ids][0]}")

Enter fullscreen mode Exit fullscreen mode

I write blogs about Computer Vision projects on my GitHub page and if you got some time please share yours too.

Discussion (2)

dustinbrownman profile image
Dustin Brown

Nicely done! I like how you kept track of the start/end as you went along. I couldn't figure out how I'd keep track of which "section" I was narrowing down to. Great work!

qviper profile image
Viper Author

Thank you a lots for the support. I found day 4's challenge more harder than this one.