2020 Advent of Code–Day 4

This series looks at the Advent of Code challenges.

As one of my goals, I’m working through challenges. This post looks at day 4. I’m going to do this one in Python here, though I did solve it in other languages in my repo.

Part 1

We have another string parsing operation. We get a series of lines that represent a passport. Passports are separated by blank lines. Therefore, we can get 1-x number of lines representing a passport.

Ugh.

Python seems like a good place to start here. I loaded the file and then started to concatenate rows of data until I found a blank one.

file_handle = open('2020\day4\day4_data.txt', 'r')
passports = file_handle.readlines()
part1 = 0
currpassport = ""
for row in passports:
if row not in ['\n','\r\n']:
        currpassport += row.replace('\n',' ')
#print(currpassport.split(" "))

else:

At this point, I have a passport I can look at, with all the various sections. I used another split, this time into a dictionary to get each item separate.

currdict = dict(x.split(":") for x in currpassport.split(" ") if x)

Now, I can count these. If there are 8, or if there are 7 and CID is one of them, I have a valid passport. Adding these up gets me the answer.

Part 2

This is very similar, but each part now needs validation. So, I take the same structure, but once I have passports, I assume they are valid and start to check each section. It’s really a series of IF statements for me.

            valid = 1
if ((int(currdict["iyr"]) < 2010) or (int(currdict["iyr"]) > 2020)):
                valid = 0
if int(currdict["byr"]) < 1920 or int(currdict["byr"]) > 2002 :
                valid = 0
if int(currdict["eyr"]) < 2020 or int(currdict["iyr"]) > 2030:
                valid = 0

These each could be functions, and I’d refactor that way, but I couldn’t come up with an easier way to do this. After checking if I have enough valid items, I tally another passport (or not).

Overall, this felt like busy work, not hard, but just a grind through each set of validation.

About way0utwest

Editor, SQLServerCentral
This entry was posted in Blog and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.