From 668449e943d226c1f316df579bb6a181418ce880 Mon Sep 17 00:00:00 2001 From: cupcakearmy Date: Fri, 4 Dec 2020 06:40:52 +0100 Subject: [PATCH] 4 --- README.md | 2 ++ solutions/4/README.md | 14 ++++++++++++ solutions/4/main.py | 52 +++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 solutions/4/README.md create mode 100644 solutions/4/main.py diff --git a/README.md b/README.md index fb78acf..80cb2b3 100644 --- a/README.md +++ b/README.md @@ -2,4 +2,6 @@ Here are my solutions for the advent of code 2020 🎄🎅 +Note that the exact solutions are different for some people. + `/solutions/:day/*` diff --git a/solutions/4/README.md b/solutions/4/README.md new file mode 100644 index 0000000..561924b --- /dev/null +++ b/solutions/4/README.md @@ -0,0 +1,14 @@ +# 4 + +This one was a lot of parsing, but nothing regexp can't do. +The first is quite straight forward, just check that all but `cid` are present. + +The second was a bit of validation for each field, but again some simple regexp and number checking and the job is done 🙂 + +
+ Solutions +
    +
  1. 206
  2. +
  3. 123
  4. +
+
diff --git a/solutions/4/main.py b/solutions/4/main.py new file mode 100644 index 0000000..9bed9ea --- /dev/null +++ b/solutions/4/main.py @@ -0,0 +1,52 @@ +from os.path import join, dirname +import re + + +def validate_chunk(chunk, extended=False): + parts = re.split(' |\n', chunk.strip()) + password = dict(map(lambda p: p.split(":"), parts)) + + required = ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'] + if not all(item in password.keys() for item in required): + return False + + if not extended: + return True + + if not 1920 <= int(password['byr']) <= 2002: + return False + if not 2010 <= int(password['iyr']) <= 2020: + return False + if not 2020 <= int(password['eyr']) <= 2030: + return False + + tmp = password['hgt'] + hgt = int(tmp[:-2]) + unit = tmp[-2:] + if not unit in ['cm', 'in']: + return False + if unit == 'cm' and not 150 <= hgt <= 193: + return False + if unit == 'in' and not 59 <= hgt <= 76: + return False + + if not re.match(r'^#[\dabcdef]{6}$', password['hcl']): + return False + if not re.match(r'^\d{9}$', password['pid']): + return False + + if password['ecl'] not in ['amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth']: + return False + return True + + +data = join(dirname(__file__), 'data.txt') +with open(data) as f: + chunks = re.split('\n\n+', f.read().strip()) + total_simple = 0 + total_extended = 0 + for chunk in chunks: + total_simple += int(validate_chunk(chunk)) + total_extended += int(validate_chunk(chunk, extended=True)) + print(f'Simple Validation:\t{total_simple}') + print(f'Extended Validation:\t{total_extended}')