[py] Port 2018_02

This commit is contained in:
Joscha 2022-12-06 15:18:41 +01:00
parent 31d6098c58
commit 167e0125ac
3 changed files with 59 additions and 64 deletions

View file

@ -1,63 +0,0 @@
import sys
def load_words(filename):
words = []
with open(filename, "r") as f:
for line in f:
words.append(line[:-1])
return words
# PART 1
def has_n_chars(word, n):
count = {}
for char in word:
count[char] = count.get(char, 0) + 1
return n in count.values()
def count_words(words):
twice = 0
thrice = 0
for word in words:
if has_n_chars(word, 2):
twice += 1
if has_n_chars(word, 3):
thrice += 1
return twice, thrice
def checksum(words):
twice, thrice = count_words(words)
return twice * thrice
# PART 2
def differ_by(a, b):
count = 0
for x, y in zip(a, b):
if x != y:
count += 1
return count
def find_ids(words):
for i, a in enumerate(words):
for b in words[i:]:
if differ_by(a, b) == 1:
return a, b
def common_chars(a, b):
result = []
for x, y in zip(a, b):
if x == y:
result.append(x)
return "".join(result)
def main(filename):
words = load_words(filename)
print(f"Solutions for {filename}")
print(f"Part 1: {checksum(words)}")
a, b = find_ids(words)
print(f"Part 2: {common_chars(a, b)}")
if __name__ == "__main__":
for filename in sys.argv[1:]:
main(filename)

View file

@ -2,13 +2,14 @@ import sys
import argparse import argparse
from pathlib import Path from pathlib import Path
from .y2018 import d01 from .y2018 import d01, d02
from .y2020 import d10 from .y2020 import d10
from .y2021 import d14 from .y2021 import d14
from .y2022 import d01, d02, d03, d04, d05, d06 from .y2022 import d01, d02, d03, d04, d05, d06
DAYS = { DAYS = {
"2018_01": y2018.d01.solve, "2018_01": y2018.d01.solve,
"2018_02": y2018.d02.solve,
"2020_10": y2020.d10.solve, "2020_10": y2020.d10.solve,
"2021_14": y2021.d14.solve, "2021_14": y2021.d14.solve,
"2022_01": y2022.d01.solve, "2022_01": y2022.d01.solve,

57
py/aoc/y2018/d02.py Normal file
View file

@ -0,0 +1,57 @@
# PART 1
def has_n_chars(word, n):
count = {}
for char in word:
count[char] = count.get(char, 0) + 1
return n in count.values()
def count_words(words):
twice = 0
thrice = 0
for word in words:
if has_n_chars(word, 2):
twice += 1
if has_n_chars(word, 3):
thrice += 1
return twice, thrice
def checksum(words):
twice, thrice = count_words(words)
return twice * thrice
# PART 2
def differ_by(a, b):
count = 0
for x, y in zip(a, b):
if x != y:
count += 1
return count
def find_ids(words):
for i, a in enumerate(words):
for b in words[i:]:
if differ_by(a, b) == 1:
return a, b
def common_chars(a, b):
result = []
for x, y in zip(a, b):
if x == y:
result.append(x)
return "".join(result)
def solve(inputstr):
words = inputstr.splitlines()
print(f"Part 1: {checksum(words)}")
a, b = find_ids(words)
print(f"Part 2: {common_chars(a, b)}")