You climb the hill and again try contacting the Elves. However, you instead receive a signal you weren't expecting: a distress signal.
Your handheld device must still not be working properly; the packets from the distress signal got decoded out of order. You'll need to re-order the list of received packets (your puzzle input) to decode the message.
Your list consists of pairs of packets; pairs are separated by a blank line. You need to identify how many pairs of packets are in the right order.
For example:
[1,1,3,1,1]
[1,1,5,1,1]
[[1],[2,3,4]]
[[1],4]
[9]
[[8,7,6]]
[[4,4],4,4]
[[4,4],4,4,4]
[7,7,7,7]
[7,7,7]
[]
[3]
[[[]]]
[[]]
[1,[2,[3,[4,[5,6,7]]]],8,9]
[1,[2,[3,[4,[5,6,0]]]],8,9]
Packet data consists of lists and integers. Each list starts with [, ends with ], and contains zero or more comma-separated values (either integers or other lists). Each packet is always a list and appears on its own line.
When comparing two values, the first value is called left and the second value is called right. Then:
Using these rules, you can determine which of the pairs in the example are in the right order:
== Pair 1 ==
- Compare [1,1,3,1,1] vs [1,1,5,1,1]
- Compare 1 vs 1
- Compare 1 vs 1
- Compare 3 vs 5
- Left side is smaller, so inputs are in the right order
== Pair 2 ==
- Compare [[1],[2,3,4]] vs [[1],4]
- Compare [1] vs [1]
- Compare 1 vs 1
- Compare [2,3,4] vs 4
- Mixed types; convert right to [4] and retry comparison
- Compare [2,3,4] vs [4]
- Compare 2 vs 4
- Left side is smaller, so inputs are in the right order
== Pair 3 ==
- Compare [9] vs [[8,7,6]]
- Compare 9 vs [8,7,6]
- Mixed types; convert left to [9] and retry comparison
- Compare [9] vs [8,7,6]
- Compare 9 vs 8
- Right side is smaller, so inputs are not in the right order
== Pair 4 ==
- Compare [[4,4],4,4] vs [[4,4],4,4,4]
- Compare [4,4] vs [4,4]
- Compare 4 vs 4
- Compare 4 vs 4
- Compare 4 vs 4
- Compare 4 vs 4
- Left side ran out of items, so inputs are in the right order
== Pair 5 ==
- Compare [7,7,7,7] vs [7,7,7]
- Compare 7 vs 7
- Compare 7 vs 7
- Compare 7 vs 7
- Right side ran out of items, so inputs are not in the right order
== Pair 6 ==
- Compare [] vs [3]
- Left side ran out of items, so inputs are in the right order
== Pair 7 ==
- Compare [[[]]] vs [[]]
- Compare [[]] vs []
- Right side ran out of items, so inputs are not in the right order
== Pair 8 ==
- Compare [1,[2,[3,[4,[5,6,7]]]],8,9] vs [1,[2,[3,[4,[5,6,0]]]],8,9]
- Compare 1 vs 1
- Compare [2,[3,[4,[5,6,7]]]] vs [2,[3,[4,[5,6,0]]]]
- Compare 2 vs 2
- Compare [3,[4,[5,6,7]]] vs [3,[4,[5,6,0]]]
- Compare 3 vs 3
- Compare [4,[5,6,7]] vs [4,[5,6,0]]
- Compare 4 vs 4
- Compare [5,6,7] vs [5,6,0]
- Compare 5 vs 5
- Compare 6 vs 6
- Compare 7 vs 0
- Right side is smaller, so inputs are not in the right order
What are the indices of the pairs that are already in the right order? (The first pair has index 1, the second pair has index 2, and so on.) In the above example, the pairs in the right order are 1, 2, 4, and 6; the sum of these indices is 13.
Determine which pairs of packets are already in the right order. What is the sum of the indices of those pairs?
# Python imports
from ast import literal_eval # safe eval
from functools import cmp_to_key # convert a comparator function to a sort key
from math import prod
from pathlib import Path
test = Path("data/day13_test.txt") # test data
data = Path("data/day13_data.txt") # puzzle data
def parse_input(fpath: Path) -> list[list]:
"""Parse puzzle input
:param fpath: path to puzzle input
"""
packets = [] # holds list of packet pairs
with fpath.open() as ifh:
packet = [] # holds packet pair
for line in [_.strip() for _ in ifh.readlines()]:
if len(line): # if there is line content, it's part of a packet
packet.append(literal_eval(line)) # let's pretend this is safe!
else: # otherwise it's a divider
packets.append(packet) # add last packet pair to packets list
packet = [] # new container for a packet pair
if len(packet): # EOF - add last packet to list
packets.append(packet)
return packets
def is_ordered(left, right) -> int:
"""Comparator function for ordering packets
:param left: left packet value
:param right: right packet value
Returns 1 if packets are ordered, 0 if equal, -1 if not ordered
"""
# Easy case: left and right values are integers
if isinstance(left, int) and isinstance(right, int):
if left < right:
return 1
elif left == right:
return 0
else: # left > right, so not ordered
return -1
# If only one of left/right is an integer, make it a list and compare
elif isinstance(left, int): # right is list
return is_ordered([left], right)
elif isinstance(right, int): # left is list
return is_ordered(left, [right])
else: # left and right are lists - compare lists
for lval, rval in zip(left, right): # iterate over paired list values...
result = is_ordered(lval, rval) # and compare them
if result != 0: # only return if an ordering is possible
return result
# ordering not possible on values, so break tie on length
if len(right) < len(left): # right side shorter: not ordered
return - 1
elif len(right) == len(left): # equal lengths: tie
return 0
elif len(right) > len(left): # left side shorter: ordered
return 1
def part1(fpath: Path) -> int:
"""Solve the puzzle
:param fpath: path to puzzle input
"""
packets = parse_input(fpath)
ordered_packets = [idx + 1 for (idx, pkt) in enumerate(packets) if is_ordered(*pkt) == 1]
return sum(ordered_packets)
part1(test)
13
part1(data)
5760
Now, you just need to put all of the packets in the right order. Disregard the blank lines in your list of received packets.
The distress signal protocol also requires that you include two additional divider packets:
[[2]] [[6]]
Using the same rules as before, organize all packets - the ones in your list of received packets as well as the two divider packets - into the correct order.
For the example above, the result of putting the packets in the correct order is:
[] [[]] [[[]]] [1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [1,[2,[3,[4,[5,6,0]]]],8,9] [1,[2,[3,[4,[5,6,7]]]],8,9] [[1],4] [[2]] [3] [[4,4],4,4] [[4,4],4,4,4] [[6]] [7,7,7] [7,7,7,7] [[8,7,6]] [9]
Afterward, locate the divider packets. To find the decoder key for this distress signal, you need to determine the indices of the two divider packets and multiply them together. (The first packet is at index 1, the second packet is at index 2, and so on.) In this example, the divider packets are 10th and 14th, and so the decoder key is 140.
Organize all of the packets into the correct order. What is the decoder key for the distress signal?
def part2(fpath: Path) -> int:
"""Solve the puzzle
:param fpath: path to puzzle input
"""
packets = parse_input(fpath) # load packet pairs
packets = [pkt for packet in packets for pkt in packet] # flatten packets
dividers = [[[2]], [[6]]]
packets += dividers # add dividers
# We can sort our packets because we have a comparator function (returns <0 for
# unordered, 0 for equal, >0 for ordered), using cmp_to_key() from functools
packets = sorted(packets, key=cmp_to_key(is_ordered), reverse=True) # sort packets
return prod([packets.index(_) + 1 for _ in dividers])
part2(test)
140
part2(data)
26670