Solution to problem 7 in Python

This commit is contained in:
David Doblas Jiménez 2022-03-12 19:23:02 +01:00
parent fd943e0d49
commit 9663ae26c6

View File

@ -22,9 +22,6 @@
# How many IPs in your puzzle input support TLS? # How many IPs in your puzzle input support TLS?
# from collections import deque
# from itertools import islice #tee
import re import re
with open("files/P7.txt") as f: with open("files/P7.txt") as f:
@ -41,13 +38,62 @@ def abba(s: str) -> bool:
def part_1() -> None: def part_1() -> None:
count = 0 tls = 0
for ip in IPs: for ip in IPs:
sn, hn = (" ".join(ip[::2]), " ".join(ip[1::2])) sn, hn = (" ".join(ip[::2]), " ".join(ip[1::2]))
if abba(sn) and not (abba(hn)): if abba(sn) and not (abba(hn)):
count += 1 tls += 1
print(count)
print(f"There are {tls} IPs supporting TLS")
# --- Part Two ---
# You would also like to know which IPs support SSL (super-secret listening).
# An IP supports SSL if it has an Area-Broadcast Accessor, or ABA, anywhere in
# the supernet sequences (outside any square bracketed sections), and a
# corresponding Byte Allocation Block, or BAB, anywhere in the hypernet
# sequences. An ABA is any three-character sequence which consists of the same
# character twice with a different character between them, such as xyx or aba.
# A corresponding BAB is the same characters but in reversed positions: yxy and
# bab, respectively.
# For example:
# aba[bab]xyz supports SSL (aba outside square brackets with corresponding
# bab within square brackets).
# xyx[xyx]xyx does not support SSL (xyx, but no corresponding yxy).
# aaa[kek]eke supports SSL (eke in supernet with corresponding kek in
# hypernet; the aaa sequence is not related, because the interior character
# must be different).
# zazbz[bzb]cdb supports SSL (zaz has no corresponding aza, but zbz has a
# corresponding bzb, even though zaz and zbz overlap).
# How many IPs in your puzzle input support SSL?
def is_aba(s: str) -> list[str]:
aba_list = []
for i0, i1, i2 in zip(s, s[1:], s[2:]):
if i0 == i2 and i0 != i1:
aba_list.append("".join([i0, i1, i2]))
return aba_list
def part_2() -> None:
ssl = 0
for ip in IPs:
sn, hn = (" ".join(ip[::2]), " ".join(ip[1::2]))
aba_list = is_aba(sn)
for aba in aba_list:
if aba[1] + aba[0] + aba[1] in hn:
ssl += 1
break
print(f"There are {ssl} IPs supporting SSL")
if __name__ == "__main__": if __name__ == "__main__":
part_1() part_1()
part_2()