DEV Community


Posted on • Updated on


Advent of Code 2020: Python Solution Day 5

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.

Oldest comments (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

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

Timeless DEV post...

Git Concepts I Wish I Knew Years Ago

The most used technology by developers is not Javascript.

It's not Python or HTML.

It hardly even gets mentioned in interviews or listed as a pre-requisite for jobs.

I'm talking about Git and version control of course.

One does not simply learn git