Advent of Code - Day 2: Password Philosophy#
Part One#
Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan.
The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. “Something’s wrong with our computers; we can’t log in!” You ask if you can take a look.
Their password database seems to be a little corrupted: some of the passwords wouldn’t have been allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen.
To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set.
For example, suppose you have the following list:
1-3 a: abcde
1-3 b: cdefg
2-9 c: ccccccccc
Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times.
In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies.
How many passwords are valid according to their policies?
Load Input data#
Note
The input data can be found here. :::
with open("../../data/advent-of-code/2020/day-2-input") as fid:
data = fid.readlines()
data = [x.strip() for x in data if x != "\n"]
data[:4], len(data)
(['6-7 z: dqzzzjbzz',
'13-16 j: jjjvjmjjkjjjjjjj',
'5-6 m: mmbmmlvmbmmgmmf',
'2-4 k: pkkl'],
1000)
Solution#
My solution consists of a single function that parses and validates a single
password and returns True
when the password is valid.
import collections
def is_valid_password(entry):
"""
Checks whether the password is valid according to the policy.
"""
required_count, letter, password = entry.split()
letter = letter.split(":")[0]
min_req_count, max_req_count = required_count.split("-")
min_req_count, max_req_count = int(min_req_count), int(max_req_count)
count = collections.Counter(password) # Get a count for each letter in the password
return min_req_count <= count[letter] <= max_req_count
Let’s validate the password in the example so as to make sure this function is working properly:
is_valid_password("1-3 a: abcde")
True
is_valid_password("1-3 b: cdefg")
False
is_valid_password("2-9 c: ccccccccc")
True
Now that we are confident this function is working properly, let’s loop over all entries in the input dataset, and count how many passwords are valid:
valid_passwords = 0
for entry in data:
if is_valid_password(entry):
valid_passwords += 1
valid_passwords
542
print(f"Out of {len(data)} passwords, {valid_passwords} are found to be valid.")
Out of 1000 passwords, 542 are found to be valid.
Part Two#
While it appears you validated the passwords correctly, they don’t seem to be what the Official Toboggan Corporate Authentication System is expecting.
The shopkeeper suddenly realizes that he just accidentally explained the password policy rules from his old job at the sled rental place down the street! The Official Toboggan Corporate Policy actually works a little differently.
Each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of “index zero”!) Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant for the purposes of policy enforcement.
Given the same example list from above:
1-3 a: abcde is valid: position 1 contains a and position 3 does not.
1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.
How many passwords are valid according to the new interpretation of the policies?
Solution#
My approach to part two is similar to my solution to part one in that I still have a single function for validating a single entry. In this function, I use a bitwise XOR operator. The Bitwise XOR sets the bits in the result to 1 if either, but not both, of the corresponding bits in the two operands is 1:
def is_valid_password(entry):
required_positions, letter, password = entry.split()
letter = letter.split(":")[0]
first_position, second_position = required_positions.split("-")
first_position, second_position = int(first_position), int(second_position)
# use bitwise XOR to make sure exactly one of the positions contains the given letter
if (password[first_position - 1] == letter) ^ (password[second_position - 1] == letter):
return True
return False
Once again, let’s make sure this function is working properly by using the three sample examples above:
is_valid_password("1-3 a: abcde")
True
is_valid_password("1-3 b: cdefg")
False
is_valid_password("2-9 c: ccccccccc")
False
It appears that this function is working…. It’s now time to count all valid passwords from our input data:
valid_passwords = 0
for entry in data:
if is_valid_password(entry):
valid_passwords += 1
print(f"Out of {len(data)} passwords, {valid_passwords} are found to be valid.")
Out of 1000 passwords, 360 are found to be valid.