Solution to problem 4 part 1 in Python
This commit is contained in:
parent
4b718f6f6c
commit
aa8ef9a099
55
src/Year_2016/P4.py
Normal file
55
src/Year_2016/P4.py
Normal file
@ -0,0 +1,55 @@
|
||||
# --- Day 4: Security Through Obscurity ---
|
||||
|
||||
# Finally, you come across an information kiosk with a list of rooms. Of
|
||||
# course, the list is encrypted and full of decoy data, but the instructions to
|
||||
# decode the list are barely hidden nearby. Better remove the decoy data first.
|
||||
|
||||
# Each room consists of an encrypted name (lowercase letters separated by
|
||||
# dashes) followed by a dash, a sector ID, and a checksum in square brackets.
|
||||
|
||||
# A room is real (not a decoy) if the checksum is the five most common letters
|
||||
# in the encrypted name, in order, with ties broken by alphabetization. For
|
||||
# example:
|
||||
|
||||
# aaaaa-bbb-z-y-x-123[abxyz] is a real room because the most common letters
|
||||
# are a (5), b (3), and then a tie between x, y, and z, which are listed
|
||||
# alphabetically.
|
||||
# a-b-c-d-e-f-g-h-987[abcde] is a real room because although the letters
|
||||
# are all tied (1 of each), the first five are listed alphabetically.
|
||||
# not-a-real-room-404[oarel] is a real room.
|
||||
# totally-real-room-200[decoy] is not.
|
||||
|
||||
# Of the real rooms from the list above, the sum of their sector IDs is 1514.
|
||||
|
||||
# What is the sum of the sector IDs of the real rooms?
|
||||
|
||||
from collections import Counter
|
||||
from typing import Tuple
|
||||
|
||||
with open("files/P4.txt") as f:
|
||||
instructions = [line for line in f.read().strip().split()]
|
||||
|
||||
|
||||
def split_instruction(instr: str) -> Tuple[str, str, str]:
|
||||
*name_, sector_id_checksum = str(instr).split("-")
|
||||
name = "".join(name_)
|
||||
sector_id, checksum = sector_id_checksum[:3], sector_id_checksum[4:-1]
|
||||
|
||||
return name, sector_id, checksum
|
||||
|
||||
|
||||
def part_1() -> None:
|
||||
count = 0
|
||||
for instruction in instructions:
|
||||
name, sector_id, checksum = split_instruction(instruction)
|
||||
# name must be sorted before counting due to problem requirements
|
||||
chars = Counter(sorted(name))
|
||||
checksum_calculated = "".join(n[0] for n in chars.most_common(5))
|
||||
if checksum_calculated == checksum:
|
||||
count += int(sector_id)
|
||||
|
||||
print(f"The sum is {count}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
part_1()
|
Loading…
Reference in New Issue
Block a user