This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Parse the input | |
data = open('input.txt').read().strip() | |
# Keep track of the last four characters received | |
last_four = [] | |
last_fourteen = [] | |
# Keep track of whether the start-of-packet marker and the | |
# start-of-message marker have been found | |
packet_marker_found = False | |
message_marker_found = False | |
# Process each character in the data | |
for i, ch in enumerate(data): | |
# Add the character to the list of last four characters | |
last_four.append(ch) | |
last_fourteen.append(ch) | |
# If we have more than four characters, remove the first one | |
if len(last_four) > 4: | |
last_four.pop(0) | |
if len(last_fourteen) > 14: | |
last_fourteen.pop(0) | |
# If the last four characters are all different and we haven't | |
# already found the start-of-packet marker, we have found | |
# a start-of-packet marker, so print the number of characters | |
# processed and mark that we have found it | |
if len(set(last_four)) == 4 and not packet_marker_found: | |
print(f"First start-of-packet marker after {i+1} characters") | |
packet_marker_found = True | |
# If the last 14 characters are all different and we haven't | |
# already found the start-of-message marker, we have found | |
# a start-of-message marker, so print the number of characters | |
# processed and mark that we have found it | |
if len(set(last_fourteen)) == 14 and not message_marker_found: | |
print(f"First start-of-message marker after {i+1} characters") | |
message_marker_found = True | |
# If we have found both markers, stop processing the input | |
if packet_marker_found and message_marker_found: | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment