task
stringlengths
0
154k
__index_level_0__
int64
0
39.2k
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? Your puzzle answer was 1,7,6,5,1,0,5,0,7. The first half of this puzzle is complete! It provides one gold star: * --- Part Two --- Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. For example: Register A: 2024 Register B: 0 Register C: 0 Program: 0,3,5,4,3,0 This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) What is the lowest positive initial value for register A that causes the program to output a copy of itself?
200
--- Day 23: Unstable Diffusion --- You enter a large crater of gray dirt where the grove is supposed to be. All around you, plants you imagine were expected to be full of fruit are instead withered and broken. A large group of Elves has formed in the middle of the grove. "...but this volcano has been dormant for months. Without ash, the fruit can't grow!" You look up to see a massive, snow-capped mountain towering above you. "It's not like there are other active volcanoes here; we've looked everywhere." "But our scanners show active magma flows; clearly it's going somewhere." They finally notice you at the edge of the grove, your pack almost overflowing from the random star fruit you've been collecting. Behind you, elephants and monkeys explore the grove, looking concerned. Then, the Elves recognize the ash cloud slowly spreading above your recent detour. "Why do you--" "How is--" "Did you just--" Before any of them can form a complete question, another Elf speaks up: "Okay, new plan. We have almost enough fruit already, and ash from the plume should spread here eventually. If we quickly plant new seedlings now, we can still make it to the extraction point. Spread out!" The Elves each reach into their pack and pull out a tiny plant. The plants rely on important nutrients from the ash, so they can't be planted too close together. There isn't enough time to let the Elves figure out where to plant the seedlings themselves; you quickly scan the grove (your puzzle input) and note their positions. For example: ....#.. ..###.# #...#.# .#...## #.###.. ##.#.## .#..#.. The scan shows Elves # and empty ground .; outside your scan, more empty ground extends a long way in every direction. The scan is oriented so that north is up; orthogonal directions are written N (north), S (south), W (west), and E (east), while diagonal directions are written NE, NW, SE, SW. The Elves follow a time-consuming process to figure out where they should each go; you can speed up this process considerably. The process consists of some number of rounds during which Elves alternate between considering where to move and actually moving. During the first half of each round, each Elf considers the eight positions adjacent to themself. If no other Elves are in one of those eight positions, the Elf does not do anything during this round. Otherwise, the Elf looks in each of four directions in the following order and proposes moving one step in the first valid direction: If there is no Elf in the N, NE, or NW adjacent positions, the Elf proposes moving north one step. If there is no Elf in the S, SE, or SW adjacent positions, the Elf proposes moving south one step. If there is no Elf in the W, NW, or SW adjacent positions, the Elf proposes moving west one step. If there is no Elf in the E, NE, or SE adjacent positions, the Elf proposes moving east one step. After each Elf has had a chance to propose a move, the second half of the round can begin. Simultaneously, each Elf moves to their proposed destination tile if they were the only Elf to propose moving to that position. If two or more Elves propose moving to the same position, none of those Elves move. Finally, at the end of the round, the first direction the Elves considered is moved to the end of the list of directions. For example, during the second round, the Elves would try proposing a move to the south first, then west, then east, then north. On the third round, the Elves would first consider west, then east, then north, then south. As a smaller example, consider just these five Elves: ..... ..##. ..#.. ..... ..##. ..... The northernmost two Elves and southernmost two Elves all propose moving north, while the middle Elf cannot move north and proposes moving south. The middle Elf proposes the same destination as the southwest Elf, so neither of them move, but the other three do: ..##. ..... ..#.. ...#. ..#.. ..... Next, the northernmost two Elves and the southernmost Elf all propose moving south. Of the remaining middle two Elves, the west one cannot move south and proposes moving west, while the east one cannot move south or west and proposes moving east. All five Elves succeed in moving to their proposed positions: ..... ..##. .#... ....# ..... ..#.. Finally, the southernmost two Elves choose not to move at all. Of the remaining three Elves, the west one proposes moving west, the east one proposes moving east, and the middle one proposes moving north; all three succeed in moving: ..#.. ....# #.... ....# ..... ..#.. At this point, no Elves need to move, and so the process ends. The larger example above proceeds as follows: == Initial State == .............. .............. .......#...... .....###.#.... ...#...#.#.... ....#...##.... ...#.###...... ...##.#.##.... ....#..#...... .............. .............. .............. == End of Round 1 == .............. .......#...... .....#...#.... ...#..#.#..... .......#..#... ....#.#.##.... ..#..#.#...... ..#.#.#.##.... .............. ....#..#...... .............. .............. == End of Round 2 == .............. .......#...... ....#.....#... ...#..#.#..... .......#...#.. ...#..#.#..... .#...#.#.#.... .............. ..#.#.#.##.... ....#..#...... .............. .............. == End of Round 3 == .............. .......#...... .....#....#... ..#..#...#.... .......#...#.. ...#..#.#..... .#..#.....#... .......##..... ..##.#....#... ...#.......... .......#...... .............. == End of Round 4 == .............. .......#...... ......#....#.. ..#...##...... ...#.....#.#.. .........#.... .#...###..#... ..#......#.... ....##....#... ....#......... .......#...... .............. == End of Round 5 == .......#...... .............. ..#..#.....#.. .........#.... ......##...#.. .#.#.####..... ...........#.. ....##..#..... ..#........... ..........#... ....#..#...... .............. After a few more rounds... == End of Round 10 == .......#...... ...........#.. ..#.#..#...... ......#....... ...#.....#..#. .#......##.... .....##....... ..#........#.. ....#.#..#.... .............. ....#..#..#... .............. To make sure they're on the right track, the Elves like to check after round 10 that they're making good progress toward covering enough ground. To do this, count the number of empty ground tiles contained by the smallest rectangle that contains every Elf. (The edges of the rectangle should be aligned to the N/S/E/W directions; the Elves do not have the patience to calculate arbitrary rectangles.) In the above example, that rectangle is: ......#..... ..........#. .#.#..#..... .....#...... ..#.....#..# #......##... ....##...... .#........#. ...#.#..#... ............ ...#..#..#.. In this region, the number of empty ground tiles is 110. Simulate the Elves' process and find the smallest rectangle that contains the Elves after 10 rounds. How many empty ground tiles does that rectangle contain?
201
--- Day 23: A Long Walk --- The Elves resume water filtering operations! Clean water starts flowing over the edge of Island Island. They offer to help you go over the edge of Island Island, too! Just hold on tight to one end of this impossibly long rope and they'll lower you down a safe distance from the massive waterfall you just created. As you finally reach Snow Island, you see that the water isn't really reaching the ground: it's being absorbed by the air itself. It looks like you'll finally have a little downtime while the moisture builds up to snow-producing levels. Snow Island is pretty scenic, even without any snow; why not take a walk? There's a map of nearby hiking trails (your puzzle input) that indicates paths (.), forest (#), and steep slopes (^, >, v, and <). For example: #.##################### #.......#########...### #######.#########.#.### ###.....#.>.>.###.#.### ###v#####.#v#.###.#.### ###.>...#.#.#.....#...# ###v###.#.#.#########.# ###...#.#.#.......#...# #####.#.#.#######.#.### #.....#.#.#.......#...# #.#####.#.#.#########v# #.#...#...#...###...>.# #.#.#v#######v###.###v# #...#.>.#...>.>.#.###.# #####v#.#.###v#.#.###.# #.....#...#...#.#.#...# #.#########.###.#.#.### #...###...#...#...#.### ###.###.#.###v#####v### #...#...#.#.>.>.#.>.### #.###.###.#.###.#.#v### #.....###...###...#...# #####################.# You're currently on the single path tile in the top row; your goal is to reach the single path tile in the bottom row. Because of all the mist from the waterfall, the slopes are probably quite icy; if you step onto a slope tile, your next step must be downhill (in the direction the arrow is pointing). To make sure you have the most scenic hike possible, never step onto the same tile twice. What is the longest hike you can take? In the example above, the longest hike you can take is marked with O, and your starting position is marked S: #S##################### #OOOOOOO#########...### #######O#########.#.### ###OOOOO#OOO>.###.#.### ###O#####O#O#.###.#.### ###OOOOO#O#O#.....#...# ###v###O#O#O#########.# ###...#O#O#OOOOOOO#...# #####.#O#O#######O#.### #.....#O#O#OOOOOOO#...# #.#####O#O#O#########v# #.#...#OOO#OOO###OOOOO# #.#.#v#######O###O###O# #...#.>.#...>OOO#O###O# #####v#.#.###v#O#O###O# #.....#...#...#O#O#OOO# #.#########.###O#O#O### #...###...#...#OOO#O### ###.###.#.###v#####O### #...#...#.#.>.>.#.>O### #.###.###.#.###.#.#O### #.....###...###...#OOO# #####################O# This hike contains 94 steps. (The other possible hikes you could have taken were 90, 86, 82, 82, and 74 steps long.) Find the longest hike you can take through the hiking trails listed on your map. How many steps long is the longest hike?
202
--- Day 17: Chronospatial Computer --- The Historians push the button on their strange device, but this time, you all just feel like you're falling. "Situation critical", the device announces in a familiar voice. "Bootstrapping process failed. Initializing debugger...." The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: Combo operands 0 through 3 represent literal values 0 through 3. Combo operand 4 represents the value of register A. Combo operand 5 represents the value of register B. Combo operand 6 represents the value of register C. Combo operand 7 is reserved and will not appear in valid programs. The eight instructions are as follows: The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) Here are some examples of instruction operation: If register C contains 9, the program 2,6 would set register B to 1. If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. If register B contains 29, the program 1,7 would set register B to 26. If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: Register A: 729 Register B: 0 Register C: 0 Program: 0,1,5,4,3,0 Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?
203
--- Day 22: Monkey Map --- The monkeys take you on a surprisingly easy trail through the jungle. They're even going in roughly the right direction according to your handheld device's Grove Positioning System. As you walk, the monkeys explain that the grove is protected by a force field. To pass through the force field, you have to enter a password; doing so involves tracing a specific path on a strangely-shaped board. At least, you're pretty sure that's what you have to do; the elephants aren't exactly fluent in monkey. The monkeys give you notes that they took when they last saw the password entered (your puzzle input). For example: ...# .#.. #... .... ...#.......# ........#... ..#....#.... ..........#. ...#.... .....#.. .#...... ......#. 10R5L5R10L4R5L5 The first half of the monkeys' notes is a map of the board. It is comprised of a set of open tiles (on which you can move, drawn .) and solid walls (tiles which you cannot enter, drawn #). The second half is a description of the path you must follow. It consists of alternating numbers and letters: A number indicates the number of tiles to move in the direction you are facing. If you run into a wall, you stop moving forward and continue with the next instruction. A letter indicates whether to turn 90 degrees clockwise (R) or counterclockwise (L). Turning happens in-place; it does not change your current tile. So, a path like 10R5 means "go forward 10 tiles, then turn clockwise 90 degrees, then go forward 5 tiles". You begin the path in the leftmost open tile of the top row of tiles. Initially, you are facing to the right (from the perspective of how the map is drawn). If a movement instruction would take you off of the map, you wrap around to the other side of the board. In other words, if your next tile is off of the board, you should instead look in the direction opposite of your current facing as far as you can until you find the opposite edge of the board, then reappear there. For example, if you are at A and facing to the right, the tile in front of you is marked B; if you are at C and facing down, the tile in front of you is marked D: ...# .#.. #... .... ...#.D.....# ........#... B.#....#...A .....C....#. ...#.... .....#.. .#...... ......#. It is possible for the next tile (after wrapping around) to be a wall; this still counts as there being a wall in front of you, and so movement stops before you actually wrap to the other side of the board. By drawing the last facing you had with an arrow on each tile you visit, the full path taken by the above example looks like this: >>v# .#v. #.v. ..v. ...#...v..v# >>>v...>#.>> ..#v...#.... ...>>>>v..#. ...#.... .....#.. .#...... ......#. To finish providing the password to this strange input device, you need to determine numbers for your final row, column, and facing as your final position appears from the perspective of the original map. Rows start from 1 at the top and count downward; columns start from 1 at the left and count rightward. (In the above example, row 1, column 1 refers to the empty space with no tile on it in the top-left corner.) Facing is 0 for right (>), 1 for down (v), 2 for left (<), and 3 for up (^). The final password is the sum of 1000 times the row, 4 times the column, and the facing. In the above example, the final row is 6, the final column is 8, and the final facing is 0. So, the final password is 1000 * 6 + 4 * 8 + 0: 6032. Follow the path given in the monkeys' notes. What is the final password?
204
--- Day 7: Internet Protocol Version 7 --- While snooping around the local network of EBHQ, you compile a list of IP addresses (they're IPv7, of course; IPv6 is much too limited). You'd like to figure out which IPs support TLS (transport-layer snooping). An IP supports TLS if it has an Autonomous Bridge Bypass Annotation, or ABBA. An ABBA is any four-character sequence which consists of a pair of two different characters followed by the reverse of that pair, such as xyyx or abba. However, the IP also must not have an ABBA within any hypernet sequences, which are contained by square brackets. For example: abba[mnop]qrst supports TLS (abba outside square brackets). abcd[bddb]xyyx does not support TLS (bddb is within square brackets, even though xyyx is outside square brackets). aaaa[qwer]tyui does not support TLS (aaaa is invalid; the interior characters must be different). ioxxoj[asdfgh]zxcvbn supports TLS (oxxo is outside square brackets, even though it's within a larger string). How many IPs in your puzzle input support TLS? Your puzzle answer was 110. --- 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?
205
--- Day 8: Memory Maneuver --- The sleigh is much easier to pull than you'd expect for something its weight. Unfortunately, neither you nor the Elves know which way the North Pole is from here. You check your wrist device for anything that might help. It seems to have some kind of navigation system! Activating the navigation system produces more bad news: "Failed to start navigation system. Could not read software license file." The navigation system's license file consists of a list of numbers (your puzzle input). The numbers define a data structure which, when processed, produces some kind of tree that can be used to calculate the license number. The tree is made up of nodes; a single, outermost node forms the tree's root, and it contains all other nodes in the tree (or contains nodes that contain nodes, and so on). Specifically, a node consists of: A header, which is always exactly two numbers: The quantity of child nodes. The quantity of metadata entries. Zero or more child nodes (as specified in the header). One or more metadata entries (as specified in the header). Each child node is itself a node that has its own header, child nodes, and metadata. For example: 2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2 A---------------------------------- B----------- C----------- D----- In this example, each node of the tree is also marked with an underline starting with a letter for easier identification. In it, there are four nodes: A, which has 2 child nodes (B, C) and 3 metadata entries (1, 1, 2). B, which has 0 child nodes and 3 metadata entries (10, 11, 12). C, which has 1 child node (D) and 1 metadata entry (2). D, which has 0 child nodes and 1 metadata entry (99). The first check done on the license file is to simply add up all of the metadata entries. In this example, that sum is 1+1+2+10+11+12+2+99=138. What is the sum of all metadata entries? Your puzzle answer was 42768. --- Part Two --- The second check is slightly more complicated: you need to find the value of the root node (A in the example above). The value of a node depends on whether it has child nodes. If a node has no child nodes, its value is the sum of its metadata entries. So, the value of node B is 10+11+12=33, and the value of node D is 99. However, if a node does have child nodes, the metadata entries become indexes which refer to those child nodes. A metadata entry of 1 refers to the first child node, 2 to the second, 3 to the third, and so on. The value of this node is the sum of the values of the child nodes referenced by the metadata entries. If a referenced child node does not exist, that reference is skipped. A child node can be referenced multiple time and counts each time it is referenced. A metadata entry of 0 does not refer to any child node. For example, again using the above nodes: Node C has one metadata entry, 2. Because node C has only one child node, 2 references a child node which does not exist, and so the value of node C is 0. Node A has three metadata entries: 1, 1, and 2. The 1 references node A's first child node, B, and the 2 references node A's second child node, C. Because node B has a value of 33 and node C has a value of 0, the value of node A is 33+33+0=66. So, in this example, the value of the root node is 66. What is the value of the root node?
206
--- Day 2: Dive! --- Now, you need to figure out how to pilot this thing. It seems like the submarine can take a series of commands like forward 1, down 2, or up 3: forward X increases the horizontal position by X units. down X increases the depth by X units. up X decreases the depth by X units. Note that since you're on a submarine, down and up affect your depth, and so they have the opposite result of what you might expect. The submarine seems to already have a planned course (your puzzle input). You should probably figure out where it's going. For example: forward 5 down 5 forward 8 up 3 down 8 forward 2 Your horizontal position and depth both start at 0. The steps above would then modify them as follows: forward 5 adds 5 to your horizontal position, a total of 5. down 5 adds 5 to your depth, resulting in a value of 5. forward 8 adds 8 to your horizontal position, a total of 13. up 3 decreases your depth by 3, resulting in a value of 2. down 8 adds 8 to your depth, resulting in a value of 10. forward 2 adds 2 to your horizontal position, a total of 15. After following these instructions, you would have a horizontal position of 15 and a depth of 10. (Multiplying these together produces 150.) Calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth? Your puzzle answer was 1451208. --- Part Two --- Based on your calculations, the planned course doesn't seem to make any sense. You find the submarine manual and discover that the process is actually slightly more complicated. In addition to horizontal position and depth, you'll also need to track a third value, aim, which also starts at 0. The commands also mean something entirely different than you first thought: down X increases your aim by X units. up X decreases your aim by X units. forward X does two things: It increases your horizontal position by X units. It increases your depth by your aim multiplied by X. Again note that since you're on a submarine, down and up do the opposite of what you might expect: "down" means aiming in the positive direction. Now, the above example does something different: forward 5 adds 5 to your horizontal position, a total of 5. Because your aim is 0, your depth does not change. down 5 adds 5 to your aim, resulting in a value of 5. forward 8 adds 8 to your horizontal position, a total of 13. Because your aim is 5, your depth increases by 8*5=40. up 3 decreases your aim by 3, resulting in a value of 2. down 8 adds 8 to your aim, resulting in a value of 10. forward 2 adds 2 to your horizontal position, a total of 15. Because your aim is 10, your depth increases by 2*10=20 to a total of 60. After following these new instructions, you would have a horizontal position of 15 and a depth of 60. (Multiplying these produces 900.) Using this new interpretation of the commands, calculate the horizontal position and depth you would have after following the planned course. What do you get if you multiply your final horizontal position by your final depth?
207
--- Day 14: Parabolic Reflector Dish --- You reach the place where all of the mirrors were pointing: a massive parabolic reflector dish attached to the side of another large mountain. The dish is made up of many small mirrors, but while the mirrors themselves are roughly in the shape of a parabolic reflector dish, each individual mirror seems to be pointing in slightly the wrong direction. If the dish is meant to focus light, all it's doing right now is sending it in a vague direction. This system must be what provides the energy for the lava! If you focus the reflector dish, maybe you can go where it's pointing and use the light to fix the lava production. Upon closer inspection, the individual mirrors each appear to be connected via an elaborate system of ropes and pulleys to a large metal platform below the dish. The platform is covered in large rocks of various shapes. Depending on their position, the weight of the rocks deforms the platform, and the shape of the platform controls which ropes move and ultimately the focus of the dish. In short: if you move the rocks, you can focus the dish. The platform even has a control panel on the side that lets you tilt it in one of four directions! The rounded rocks (O) will roll when the platform is tilted, while the cube-shaped rocks (#) will stay in place. You note the positions of all of the empty spaces (.) and rocks (your puzzle input). For example: O....#.... O.OO#....# .....##... OO.#O....O .O.....O#. O.#..O.#.# ..O..#O..O .......O.. #....###.. #OO..#.... Start by tilting the lever so all of the rocks will slide north as far as they will go: OOOO.#.O.. OO..#....# OO..O##..O O..#.OO... ........#. ..#....#.# ..O..#.O.O ..O....... #....###.. #....#.... You notice that the support beams along the north side of the platform are damaged; to ensure the platform doesn't collapse, you should calculate the total load on the north support beams. The amount of load caused by a single rounded rock (O) is equal to the number of rows from the rock to the south edge of the platform, including the row the rock is on. (Cube-shaped rocks (#) don't contribute to load.) So, the amount of load caused by each rock in each row is as follows: OOOO.#.O.. 10 OO..#....# 9 OO..O##..O 8 O..#.OO... 7 ........#. 6 ..#....#.# 5 ..O..#.O.O 4 ..O....... 3 #....###.. 2 #....#.... 1 The total load is the sum of the load caused by all of the rounded rocks. In this example, the total load is 136. Tilt the platform so that the rounded rocks all roll north. Afterward, what is the total load on the north support beams?
208
--- Day 16: Aunt Sue --- Your Aunt Sue has given you a wonderful gift, and you'd like to send her a thank you card. However, there's a small problem: she signed it "From, Aunt Sue". You have 500 Aunts named "Sue". So, to avoid sending the card to the wrong person, you need to figure out which Aunt Sue (which you conveniently number 1 to 500, for sanity) gave you the gift. You open the present and, as luck would have it, good ol' Aunt Sue got you a My First Crime Scene Analysis Machine! Just what you wanted. Or needed, as the case may be. The My First Crime Scene Analysis Machine (MFCSAM for short) can detect a few specific compounds in a given sample, as well as how many distinct kinds of those compounds there are. According to the instructions, these are what the MFCSAM can detect: children, by human DNA age analysis. cats. It doesn't differentiate individual breeds. Several seemingly random breeds of dog: samoyeds, pomeranians, akitas, and vizslas. goldfish. No other kinds of fish. trees, all in one group. cars, presumably by exhaust or gasoline or something. perfumes, which is handy, since many of your Aunts Sue wear a few kinds. In fact, many of your Aunts Sue have many of these. You put the wrapping from the gift into the MFCSAM. It beeps inquisitively at you a few times and then prints out a message on ticker tape: children: 3 cats: 7 samoyeds: 2 pomeranians: 3 akitas: 0 vizslas: 0 goldfish: 5 trees: 3 cars: 2 perfumes: 1 You make a list of the things you can remember about each Aunt Sue. Things missing from your list aren't zero - you simply don't remember the value. What is the number of the Sue that got you the gift? Your puzzle answer was 373. --- Part Two --- As you're about to send the thank you note, something in the MFCSAM's instructions catches your eye. Apparently, it has an outdated retroencabulator, and so the output from the machine isn't exact values - some of them indicate ranges. In particular, the cats and trees readings indicates that there are greater than that many (due to the unpredictable nuclear decay of cat dander and tree pollen), while the pomeranians and goldfish readings indicate that there are fewer than that many (due to the modial interaction of magnetoreluctance). What is the number of the real Aunt Sue?
209
--- Day 21: Step Counter --- You manage to catch the airship right as it's dropping someone else off on their all-expenses-paid trip to Desert Island! It even helpfully drops you off near the gardener and his massive farm. "You got the sand flowing again! Great work! Now we just need to wait until we have enough sand to filter the water for Snow Island and we'll have snow again in no time." While you wait, one of the Elves that works with the gardener heard how good you are at solving problems and would like your help. He needs to get his steps in for the day, and so he'd like to know which garden plots he can reach with exactly his remaining 64 steps. He gives you an up-to-date map (your puzzle input) of his starting position (S), garden plots (.), and rocks (#). For example: ........... .....###.#. .###.##..#. ..#.#...#.. ....#.#.... .##..S####. .##..#...#. .......##.. .##.#.####. .##..##.##. ........... The Elf starts at the starting position (S) which also counts as a garden plot. Then, he can take one step north, south, east, or west, but only onto tiles that are garden plots. This would allow him to reach any of the tiles marked O: ........... .....###.#. .###.##..#. ..#.#...#.. ....#O#.... .##.OS####. .##..#...#. .......##.. .##.#.####. .##..##.##. ........... Then, he takes a second step. Since at this point he could be at either tile marked O, his second step would allow him to reach any garden plot that is one step north, south, east, or west of any tile that he could have reached after the first step: ........... .....###.#. .###.##..#. ..#.#O..#.. ....#.#.... .##O.O####. .##.O#...#. .......##.. .##.#.####. .##..##.##. ........... After two steps, he could be at any of the tiles marked O above, including the starting position (either by going north-then-south or by going west-then-east). A single third step leads to even more possibilities: ........... .....###.#. .###.##..#. ..#.#.O.#.. ...O#O#.... .##.OS####. .##O.#...#. ....O..##.. .##.#.####. .##..##.##. ........... He will continue like this until his steps for the day have been exhausted. After a total of 6 steps, he could reach any of the garden plots marked O: ........... .....###.#. .###.##.O#. .O#O#O.O#.. O.O.#.#.O.. .##O.O####. .##.O#O..#. .O.O.O.##.. .##.#.####. .##O.##.##. ........... In this example, if the Elf's goal was to get exactly 6 more steps today, he could use them to reach any of 16 garden plots. However, the Elf actually needs to get 64 steps today, and the map he's handed you is much larger than the example map. Starting from the garden plot marked S on your map, how many garden plots could the Elf reach in exactly 64 steps?
210
--- Day 16: Packet Decoder --- As you leave the cave and reach open waters, you receive a transmission from the Elves back on the ship. The transmission was sent using the Buoyancy Interchange Transmission System (BITS), a method of packing numeric expressions into a binary sequence. Your submarine's computer has saved the transmission in hexadecimal (your puzzle input). The first step of decoding the message is to convert the hexadecimal representation into binary. Each character of hexadecimal corresponds to four bits of binary data: 0 = 0000 1 = 0001 2 = 0010 3 = 0011 4 = 0100 5 = 0101 6 = 0110 7 = 0111 8 = 1000 9 = 1001 A = 1010 B = 1011 C = 1100 D = 1101 E = 1110 F = 1111 The BITS transmission contains a single packet at its outermost layer which itself contains many other packets. The hexadecimal representation of this packet might encode a few extra 0 bits at the end; these are not part of the transmission and should be ignored. Every packet begins with a standard header: the first three bits encode the packet version, and the next three bits encode the packet type ID. These two values are numbers; all numbers encoded in any packet are represented as binary with the most significant bit first. For example, a version encoded as the binary sequence 100 represents the number 4. Packets with type ID 4 represent a literal value. Literal value packets encode a single binary number. To do this, the binary number is padded with leading zeroes until its length is a multiple of four bits, and then it is broken into groups of four bits. Each group is prefixed by a 1 bit except the last group, which is prefixed by a 0 bit. These groups of five bits immediately follow the packet header. For example, the hexadecimal string D2FE28 becomes: 110100101111111000101000 VVVTTTAAAAABBBBBCCCCC Below each bit is a label indicating its purpose: The three bits labeled V (110) are the packet version, 6. The three bits labeled T (100) are the packet type ID, 4, which means the packet is a literal value. The five bits labeled A (10111) start with a 1 (not the last group, keep reading) and contain the first four bits of the number, 0111. The five bits labeled B (11110) start with a 1 (not the last group, keep reading) and contain four more bits of the number, 1110. The five bits labeled C (00101) start with a 0 (last group, end of packet) and contain the last four bits of the number, 0101. The three unlabeled 0 bits at the end are extra due to the hexadecimal representation and should be ignored. So, this packet represents a literal value with binary representation 011111100101, which is 2021 in decimal. Every other type of packet (any packet with a type ID other than 4) represent an operator that performs some calculation on one or more sub-packets contained within. Right now, the specific operations aren't important; focus on parsing the hierarchy of sub-packets. An operator packet contains one or more packets. To indicate which subsequent binary data represents its sub-packets, an operator packet can use one of two modes indicated by the bit immediately after the packet header; this is called the length type ID: If the length type ID is 0, then the next 15 bits are a number that represents the total length in bits of the sub-packets contained by this packet. If the length type ID is 1, then the next 11 bits are a number that represents the number of sub-packets immediately contained by this packet. Finally, after the length type ID bit and the 15-bit or 11-bit field, the sub-packets appear. For example, here is an operator packet (hexadecimal string 38006F45291200) with length type ID 0 that contains two sub-packets: 00111000000000000110111101000101001010010001001000000000 VVVTTTILLLLLLLLLLLLLLLAAAAAAAAAAABBBBBBBBBBBBBBBB The three bits labeled V (001) are the packet version, 1. The three bits labeled T (110) are the packet type ID, 6, which means the packet is an operator. The bit labeled I (0) is the length type ID, which indicates that the length is a 15-bit number representing the number of bits in the sub-packets. The 15 bits labeled L (000000000011011) contain the length of the sub-packets in bits, 27. The 11 bits labeled A contain the first sub-packet, a literal value representing the number 10. The 16 bits labeled B contain the second sub-packet, a literal value representing the number 20. After reading 11 and 16 bits of sub-packet data, the total length indicated in L (27) is reached, and so parsing of this packet stops. As another example, here is an operator packet (hexadecimal string EE00D40C823060) with length type ID 1 that contains three sub-packets: 11101110000000001101010000001100100000100011000001100000 VVVTTTILLLLLLLLLLLAAAAAAAAAAABBBBBBBBBBBCCCCCCCCCCC The three bits labeled V (111) are the packet version, 7. The three bits labeled T (011) are the packet type ID, 3, which means the packet is an operator. The bit labeled I (1) is the length type ID, which indicates that the length is a 11-bit number representing the number of sub-packets. The 11 bits labeled L (00000000011) contain the number of sub-packets, 3. The 11 bits labeled A contain the first sub-packet, a literal value representing the number 1. The 11 bits labeled B contain the second sub-packet, a literal value representing the number 2. The 11 bits labeled C contain the third sub-packet, a literal value representing the number 3. After reading 3 complete sub-packets, the number of sub-packets indicated in L (3) is reached, and so parsing of this packet stops. For now, parse the hierarchy of the packets throughout the transmission and add up all of the version numbers. Here are a few more examples of hexadecimal-encoded transmissions: 8A004A801A8002F478 represents an operator packet (version 4) which contains an operator packet (version 1) which contains an operator packet (version 5) which contains a literal value (version 6); this packet has a version sum of 16. 620080001611562C8802118E34 represents an operator packet (version 3) which contains two sub-packets; each sub-packet is an operator packet that contains two literal values. This packet has a version sum of 12. C0015000016115A2E0802F182340 has the same structure as the previous example, but the outermost packet uses a different length type ID. This packet has a version sum of 23. A0016C880162017C3686B18A3D4780 is an operator packet that contains an operator packet that contains an operator packet that contains five literal values; it has a version sum of 31. Decode the structure of your hexadecimal-encoded BITS transmission; what do you get if you add up the version numbers in all packets?
211
--- Day 19: Monster Messages --- You land in an airport surrounded by dense forest. As you walk to your high-speed train, the Elves at the Mythical Information Bureau contact you again. They think their satellite has collected an image of a sea monster! Unfortunately, the connection to the satellite is having problems, and many of the messages sent back from the satellite have been corrupted. They sent you a list of the rules valid messages should obey and a list of received messages they've collected so far (your puzzle input). The rules for valid messages (the top part of your puzzle input) are numbered and build upon each other. For example: 0: 1 2 1: "a" 2: 1 3 | 3 1 3: "b" Some rules, like 3: "b", simply match a single character (in this case, b). The remaining rules list the sub-rules that must be followed; for example, the rule 0: 1 2 means that to match rule 0, the text being checked must match rule 1, and the text after the part that matched rule 1 must then match rule 2. Some of the rules have multiple lists of sub-rules separated by a pipe (|). This means that at least one list of sub-rules must match. (The ones that match might be different each time the rule is encountered.) For example, the rule 2: 1 3 | 3 1 means that to match rule 2, the text being checked must match rule 1 followed by rule 3 or it must match rule 3 followed by rule 1. Fortunately, there are no loops in the rules, so the list of possible matches will be finite. Since rule 1 matches a and rule 3 matches b, rule 2 matches either ab or ba. Therefore, rule 0 matches aab or aba. Here's a more interesting example: 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" Here, because rule 4 matches a and rule 5 matches b, rule 2 matches two letters that are the same (aa or bb), and rule 3 matches two letters that are different (ab or ba). Since rule 1 matches rules 2 and 3 once each in either order, it must match two pairs of letters, one pair with matching letters and one pair with different letters. This leaves eight possibilities: aaab, aaba, bbab, bbba, abaa, abbb, baaa, or babb. Rule 0, therefore, matches a (rule 4), then any of the eight options from rule 1, then b (rule 5): aaaabb, aaabab, abbabb, abbbab, aabaab, aabbbb, abaaab, or ababbb. The received messages (the bottom part of your puzzle input) need to be checked against the rules so you can determine which are valid and which are corrupted. Including the rules and the messages together, this might look like: 0: 4 1 5 1: 2 3 | 3 2 2: 4 4 | 5 5 3: 4 5 | 5 4 4: "a" 5: "b" ababbb bababa abbbab aaabbb aaaabbb Your goal is to determine the number of messages that completely match rule 0. In the above example, ababbb and abbbab match, but bababa, aaabbb, and aaaabbb do not, producing the answer 2. The whole message must match all of rule 0; there can't be extra unmatched characters in the message. (For example, aaaabbb might appear to match rule 0 above, but it has an extra unmatched b on the end.) How many messages completely match rule 0? Your puzzle answer was 122. --- Part Two --- As you look over the list of messages, you realize your matching rules aren't quite right. To fix them, completely replace rules 8: 42 and 11: 42 31 with the following: 8: 42 | 42 8 11: 42 31 | 42 11 31 This small change has a big impact: now, the rules do contain loops, and the list of messages they could hypothetically match is infinite. You'll need to determine how these changes affect which messages are valid. Fortunately, many of the rules are unaffected by this change; it might help to start by looking at which rules always match the same set of values and how those rules (especially rules 42 and 31) are used by the new versions of rules 8 and 11. (Remember, you only need to handle the rules you have; building a solution that could handle any hypothetical combination of rules would be significantly more difficult.) For example: 42: 9 14 | 10 1 9: 14 27 | 1 26 10: 23 14 | 28 1 1: "a" 11: 42 31 5: 1 14 | 15 1 19: 14 1 | 14 14 12: 24 14 | 19 1 16: 15 1 | 14 14 31: 14 17 | 1 13 6: 14 14 | 1 14 2: 1 24 | 14 4 0: 8 11 13: 14 3 | 1 12 15: 1 | 14 17: 14 2 | 1 7 23: 25 1 | 22 14 28: 16 1 4: 1 1 20: 14 14 | 1 15 3: 5 14 | 16 1 27: 1 6 | 14 18 14: "b" 21: 14 1 | 1 14 25: 1 1 | 1 14 22: 14 14 8: 42 26: 14 22 | 1 20 18: 15 15 7: 14 5 | 1 21 24: 14 1 abbbbbabbbaaaababbaabbbbabababbbabbbbbbabaaaa bbabbbbaabaabba babbbbaabbbbbabbbbbbaabaaabaaa aaabbbbbbaaaabaababaabababbabaaabbababababaaa bbbbbbbaaaabbbbaaabbabaaa bbbababbbbaaaaaaaabbababaaababaabab ababaaaaaabaaab ababaaaaabbbaba baabbaaaabbaaaababbaababb abbbbabbbbaaaababbbbbbaaaababb aaaaabbaabaaaaababaa aaaabbaaaabbaaa aaaabbaabbaaaaaaabbbabbbaaabbaabaaa babaaabbbaaabaababbaabababaaab aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba Without updating rules 8 and 11, these rules only match three messages: bbabbbbaabaabba, ababaaaaaabaaab, and ababaaaaabbbaba. However, after updating rules 8 and 11, a total of 12 messages match: bbabbbbaabaabba babbbbaabbbbbabbbbbbaabaaabaaa aaabbbbbbaaaabaababaabababbabaaabbababababaaa bbbbbbbaaaabbbbaaabbabaaa bbbababbbbaaaaaaaabbababaaababaabab ababaaaaaabaaab ababaaaaabbbaba baabbaaaabbaaaababbaababb abbbbabbbbaaaababbbbbbaaaababb aaaaabbaabaaaaababaa aaaabbaabbaaaaaaabbbabbbaaabbaabaaa aabbbbbaabbbaaaaaabbbbbababaaaaabbaaabba After updating rules 8 and 11, how many messages completely match rule 0?
212
--- Day 24: Never Tell Me The Odds --- It seems like something is going wrong with the snow-making process. Instead of forming snow, the water that's been absorbed into the air seems to be forming hail! Maybe there's something you can do to break up the hailstones? Due to strong, probably-magical winds, the hailstones are all flying through the air in perfectly linear trajectories. You make a note of each hailstone's position and velocity (your puzzle input). For example: 19, 13, 30 @ -2, 1, -2 18, 19, 22 @ -1, -1, -2 20, 25, 34 @ -2, -2, -4 12, 31, 28 @ -1, -2, -1 20, 19, 15 @ 1, -5, -3 Each line of text corresponds to the position and velocity of a single hailstone. The positions indicate where the hailstones are right now (at time 0). The velocities are constant and indicate exactly how far each hailstone will move in one nanosecond. Each line of text uses the format px py pz @ vx vy vz. For instance, the hailstone specified by 20, 19, 15 @ 1, -5, -3 has initial X position 20, Y position 19, Z position 15, X velocity 1, Y velocity -5, and Z velocity -3. After one nanosecond, the hailstone would be at 21, 14, 12. Perhaps you won't have to do anything. How likely are the hailstones to collide with each other and smash into tiny ice crystals? To estimate this, consider only the X and Y axes; ignore the Z axis. Looking forward in time, how many of the hailstones' paths will intersect within a test area? (The hailstones themselves don't have to collide, just test for intersections between the paths they will trace.) In this example, look for intersections that happen with an X and Y position each at least 7 and at most 27; in your actual data, you'll need to check a much larger test area. Comparing all pairs of hailstones' future paths produces the following results: Hailstone A: 19, 13, 30 @ -2, 1, -2 Hailstone B: 18, 19, 22 @ -1, -1, -2 Hailstones' paths will cross inside the test area (at x=14.333, y=15.333). Hailstone A: 19, 13, 30 @ -2, 1, -2 Hailstone B: 20, 25, 34 @ -2, -2, -4 Hailstones' paths will cross inside the test area (at x=11.667, y=16.667). Hailstone A: 19, 13, 30 @ -2, 1, -2 Hailstone B: 12, 31, 28 @ -1, -2, -1 Hailstones' paths will cross outside the test area (at x=6.2, y=19.4). Hailstone A: 19, 13, 30 @ -2, 1, -2 Hailstone B: 20, 19, 15 @ 1, -5, -3 Hailstones' paths crossed in the past for hailstone A. Hailstone A: 18, 19, 22 @ -1, -1, -2 Hailstone B: 20, 25, 34 @ -2, -2, -4 Hailstones' paths are parallel; they never intersect. Hailstone A: 18, 19, 22 @ -1, -1, -2 Hailstone B: 12, 31, 28 @ -1, -2, -1 Hailstones' paths will cross outside the test area (at x=-6, y=-5). Hailstone A: 18, 19, 22 @ -1, -1, -2 Hailstone B: 20, 19, 15 @ 1, -5, -3 Hailstones' paths crossed in the past for both hailstones. Hailstone A: 20, 25, 34 @ -2, -2, -4 Hailstone B: 12, 31, 28 @ -1, -2, -1 Hailstones' paths will cross outside the test area (at x=-2, y=3). Hailstone A: 20, 25, 34 @ -2, -2, -4 Hailstone B: 20, 19, 15 @ 1, -5, -3 Hailstones' paths crossed in the past for hailstone B. Hailstone A: 12, 31, 28 @ -1, -2, -1 Hailstone B: 20, 19, 15 @ 1, -5, -3 Hailstones' paths crossed in the past for both hailstones. So, in this example, 2 hailstones' future paths cross inside the boundaries of the test area. However, you'll need to search a much larger test area if you want to see if any hailstones might collide. Look for intersections that happen with an X and Y position each at least 200000000000000 and at most 400000000000000. Disregard the Z axis entirely. Considering only the X and Y axes, check all pairs of hailstones' future paths for intersections. How many of these intersections occur within the test area? Your puzzle answer was 17867. --- Part Two --- Upon further analysis, it doesn't seem like any hailstones will naturally collide. It's up to you to fix that! You find a rock on the ground nearby. While it seems extremely unlikely, if you throw it just right, you should be able to hit every hailstone in a single throw! You can use the probably-magical winds to reach any integer position you like and to propel the rock at any integer velocity. Now including the Z axis in your calculations, if you throw the rock at time 0, where do you need to be so that the rock perfectly collides with every hailstone? Due to probably-magical inertia, the rock won't slow down or change direction when it collides with a hailstone. In the example above, you can achieve this by moving to position 24, 13, 10 and throwing the rock at velocity -3, 1, 2. If you do this, you will hit every hailstone as follows: Hailstone: 19, 13, 30 @ -2, 1, -2 Collision time: 5 Collision position: 9, 18, 20 Hailstone: 18, 19, 22 @ -1, -1, -2 Collision time: 3 Collision position: 15, 16, 16 Hailstone: 20, 25, 34 @ -2, -2, -4 Collision time: 4 Collision position: 12, 17, 18 Hailstone: 12, 31, 28 @ -1, -2, -1 Collision time: 6 Collision position: 6, 19, 22 Hailstone: 20, 19, 15 @ 1, -5, -3 Collision time: 1 Collision position: 21, 14, 12 Above, each hailstone is identified by its initial position and its velocity. Then, the time and position of that hailstone's collision with your rock are given. After 1 nanosecond, the rock has exactly the same position as one of the hailstones, obliterating it into ice dust! Another hailstone is smashed to bits two nanoseconds after that. After a total of 6 nanoseconds, all of the hailstones have been destroyed. So, at time 0, the rock needs to be at X position 24, Y position 13, and Z position 10. Adding these three coordinates together produces 47. (Don't add any coordinates from the rock's velocity.) Determine the exact position and velocity the rock needs to have at time 0 so that it perfectly collides with every hailstone. What do you get if you add up the X, Y, and Z coordinates of that initial position?
213
--- Day 9: Rope Bridge --- This rope bridge creaks as you walk along it. You aren't sure how old it is, or whether it can even support your weight. It seems to support the Elves just fine, though. The bridge spans a gorge which was carved out by the massive river far below you. You step carefully; as you do, the ropes stretch and twist. You decide to distract yourself by modeling rope physics; maybe you can even figure out where not to step. Consider a rope with a knot at each end; these knots mark the head and the tail of the rope. If the head moves far enough away from the tail, the tail is pulled toward the head. Due to nebulous reasoning involving Planck lengths, you should be able to model the positions of the knots on a two-dimensional grid. Then, by following a hypothetical series of motions (your puzzle input) for the head, you can determine how the tail will move. Due to the aforementioned Planck lengths, the rope must be quite short; in fact, the head (H) and tail (T) must always be touching (diagonally adjacent and even overlapping both count as touching): .... .TH. .... .... .H.. ..T. .... ... .H. (H covers T) ... If the head is ever two steps directly up, down, left, or right from the tail, the tail must also move one step in that direction so it remains close enough: ..... ..... ..... .TH.. -> .T.H. -> ..TH. ..... ..... ..... ... ... ... .T. .T. ... .H. -> ... -> .T. ... .H. .H. ... ... ... Otherwise, if the head and tail aren't touching and aren't in the same row or column, the tail always moves one step diagonally to keep up: ..... ..... ..... ..... ..H.. ..H.. ..H.. -> ..... -> ..T.. .T... .T... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..H.. -> ...H. -> ..TH. .T... .T... ..... ..... ..... ..... You just need to work out where the tail goes as the head follows a series of motions. Assume the head and the tail both start at the same position, overlapping. For example: R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2 This series of motions moves the head right four steps, then up four steps, then left three steps, then down one step, and so on. After each step, you'll need to update the position of the tail if the step means the head is no longer adjacent to the tail. Visually, these motions occur as follows (s marks the starting position as a reference point): == Initial State == ...... ...... ...... ...... H..... (H covers T, s) == R 4 == ...... ...... ...... ...... TH.... (T covers s) ...... ...... ...... ...... sTH... ...... ...... ...... ...... s.TH.. ...... ...... ...... ...... s..TH. == U 4 == ...... ...... ...... ....H. s..T.. ...... ...... ....H. ....T. s..... ...... ....H. ....T. ...... s..... ....H. ....T. ...... ...... s..... == L 3 == ...H.. ....T. ...... ...... s..... ..HT.. ...... ...... ...... s..... .HT... ...... ...... ...... s..... == D 1 == ..T... .H.... ...... ...... s..... == R 4 == ..T... ..H... ...... ...... s..... ..T... ...H.. ...... ...... s..... ...... ...TH. ...... ...... s..... ...... ....TH ...... ...... s..... == D 1 == ...... ....T. .....H ...... s..... == L 5 == ...... ....T. ....H. ...... s..... ...... ....T. ...H.. ...... s..... ...... ...... ..HT.. ...... s..... ...... ...... .HT... ...... s..... ...... ...... HT.... ...... s..... == R 2 == ...... ...... .H.... (H covers T) ...... s..... ...... ...... .TH... ...... s..... After simulating the rope, you can count up all of the positions the tail visited at least once. In this diagram, s again marks the starting position (which the tail also visited) and # marks other positions the tail visited: ..##.. ...##. .####. ....#. s###.. So, there are 13 positions the tail visited at least once. Simulate your complete hypothetical series of motions. How many positions does the tail of the rope visit at least once? Your puzzle answer was 6332. --- Part Two --- A rope snaps! Suddenly, the river is getting a lot closer than you remember. The bridge is still there, but some of the ropes that broke are now whipping toward you as you fall through the air! The ropes are moving too quickly to grab; you only have a few seconds to choose how to arch your body to avoid being hit. Fortunately, your simulation can be extended to support longer ropes. Rather than two knots, you now must simulate a rope consisting of ten knots. One knot is still the head of the rope and moves according to the series of motions. Each knot further down the rope follows the knot in front of it using the same rules as before. Using the same series of motions as the above example, but with the knots marked H, 1, 2, ..., 9, the motions now occur as follows: == Initial State == ...... ...... ...... ...... H..... (H covers 1, 2, 3, 4, 5, 6, 7, 8, 9, s) == R 4 == ...... ...... ...... ...... 1H.... (1 covers 2, 3, 4, 5, 6, 7, 8, 9, s) ...... ...... ...... ...... 21H... (2 covers 3, 4, 5, 6, 7, 8, 9, s) ...... ...... ...... ...... 321H.. (3 covers 4, 5, 6, 7, 8, 9, s) ...... ...... ...... ...... 4321H. (4 covers 5, 6, 7, 8, 9, s) == U 4 == ...... ...... ...... ....H. 4321.. (4 covers 5, 6, 7, 8, 9, s) ...... ...... ....H. .4321. 5..... (5 covers 6, 7, 8, 9, s) ...... ....H. ....1. .432.. 5..... (5 covers 6, 7, 8, 9, s) ....H. ....1. ..432. .5.... 6..... (6 covers 7, 8, 9, s) == L 3 == ...H.. ....1. ..432. .5.... 6..... (6 covers 7, 8, 9, s) ..H1.. ...2.. ..43.. .5.... 6..... (6 covers 7, 8, 9, s) .H1... ...2.. ..43.. .5.... 6..... (6 covers 7, 8, 9, s) == D 1 == ..1... .H.2.. ..43.. .5.... 6..... (6 covers 7, 8, 9, s) == R 4 == ..1... ..H2.. ..43.. .5.... 6..... (6 covers 7, 8, 9, s) ..1... ...H.. (H covers 2) ..43.. .5.... 6..... (6 covers 7, 8, 9, s) ...... ...1H. (1 covers 2) ..43.. .5.... 6..... (6 covers 7, 8, 9, s) ...... ...21H ..43.. .5.... 6..... (6 covers 7, 8, 9, s) == D 1 == ...... ...21. ..43.H .5.... 6..... (6 covers 7, 8, 9, s) == L 5 == ...... ...21. ..43H. .5.... 6..... (6 covers 7, 8, 9, s) ...... ...21. ..4H.. (H covers 3) .5.... 6..... (6 covers 7, 8, 9, s) ...... ...2.. ..H1.. (H covers 4; 1 covers 3) .5.... 6..... (6 covers 7, 8, 9, s) ...... ...2.. .H13.. (1 covers 4) .5.... 6..... (6 covers 7, 8, 9, s) ...... ...... H123.. (2 covers 4) .5.... 6..... (6 covers 7, 8, 9, s) == R 2 == ...... ...... .H23.. (H covers 1; 2 covers 4) .5.... 6..... (6 covers 7, 8, 9, s) ...... ...... .1H3.. (H covers 2, 4) .5.... 6..... (6 covers 7, 8, 9, s) Now, you need to keep track of the positions the new tail, 9, visits. In this example, the tail never moves, and so it only visits 1 position. However, be careful: more types of motion are possible than before, so you might want to visually compare your simulated rope to the one above. Here's a larger example: R 5 U 8 L 8 D 3 R 17 D 10 L 25 U 20 These motions occur as follows (individual steps are not shown): == Initial State == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ...........H.............. (H covers 1, 2, 3, 4, 5, 6, 7, 8, 9, s) .......................... .......................... .......................... .......................... .......................... == R 5 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ...........54321H......... (5 covers 6, 7, 8, 9, s) .......................... .......................... .......................... .......................... .......................... == U 8 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... ................H......... ................1......... ................2......... ................3......... ...............54......... ..............6........... .............7............ ............8............. ...........9.............. (9 covers s) .......................... .......................... .......................... .......................... .......................... == L 8 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... ........H1234............. ............5............. ............6............. ............7............. ............8............. ............9............. .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... .......................... == D 3 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .........2345............. ........1...6............. ........H...7............. ............8............. ............9............. .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... .......................... == R 17 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ................987654321H .......................... .......................... .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... .......................... == D 10 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ...........s.........98765 .........................4 .........................3 .........................2 .........................1 .........................H == L 25 == .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... H123456789................ == U 20 == H......................... 1......................... 2......................... 3......................... 4......................... 5......................... 6......................... 7......................... 8......................... 9......................... .......................... .......................... .......................... .......................... .......................... ...........s.............. .......................... .......................... .......................... .......................... .......................... Now, the tail (9) visits 36 positions (including s) at least once: .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... .......................... #......................... #.............###......... #............#...#........ .#..........#.....#....... ..#..........#.....#...... ...#........#.......#..... ....#......s.........#.... .....#..............#..... ......#............#...... .......#..........#....... ........#........#........ .........########......... Simulate your complete series of motions on a larger rope with ten knots. How many positions does the tail of the rope visit at least once?
214
--- Day 4: Scratchcards --- The gondola takes you up. Strangely, though, the ground doesn't seem to be coming with you; you're not climbing a mountain. As the circle of Snow Island recedes below you, an entire new landmass suddenly appears above you! The gondola carries you to the surface of the new island and lurches into the station. As you exit the gondola, the first thing you notice is that the air here is much warmer than it was on Snow Island. It's also quite humid. Is this where the water source is? The next thing you notice is an Elf sitting on the floor across the station in what seems to be a pile of colorful square cards. "Oh! Hello!" The Elf excitedly runs over to you. "How may I be of service?" You ask about water sources. "I'm not sure; I just operate the gondola lift. That does sound like something we'd have, though - this is Island Island, after all! I bet the gardener would know. He's on a different island, though - er, the small kind surrounded by water, not the floating kind. We really need to come up with a better naming scheme. Tell you what: if you can help me with something quick, I'll let you borrow my boat and you can go visit the gardener. I got all these scratchcards as a gift, but I can't figure out what I've won." The Elf leads you over to the pile of colorful cards. There, you discover dozens of scratchcards, all with their opaque covering already scratched off. Picking one up, it looks like each card has two lists of numbers separated by a vertical bar (|): a list of winning numbers and then a list of numbers you have. You organize the information into a table (your puzzle input). As far as the Elf has been able to figure out, you have to figure out which of the numbers you have appear in the list of winning numbers. The first match makes the card worth one point and each match after the first doubles the point value of that card. For example: Card 1: 41 48 83 86 17 | 83 86 6 31 17 9 48 53 Card 2: 13 32 20 16 61 | 61 30 68 82 17 32 24 19 Card 3: 1 21 53 59 44 | 69 82 63 72 16 21 14 1 Card 4: 41 92 73 84 69 | 59 84 76 51 58 5 54 83 Card 5: 87 83 26 28 32 | 88 30 70 12 93 22 82 36 Card 6: 31 18 13 56 72 | 74 77 10 23 35 67 36 11 In the above example, card 1 has five winning numbers (41, 48, 83, 86, and 17) and eight numbers you have (83, 86, 6, 31, 17, 9, 48, and 53). Of the numbers you have, four of them (48, 83, 17, and 86) are winning numbers! That means card 1 is worth 8 points (1 for the first match, then doubled three times for each of the three matches after the first). Card 2 has two winning numbers (32 and 61), so it is worth 2 points. Card 3 has two winning numbers (1 and 21), so it is worth 2 points. Card 4 has one winning number (84), so it is worth 1 point. Card 5 has no winning numbers, so it is worth no points. Card 6 has no winning numbers, so it is worth no points. So, in this example, the Elf's pile of scratchcards is worth 13 points. Take a seat in the large pile of colorful cards. How many points are they worth in total?
215
--- Day 14: Disk Defragmentation --- Suddenly, a scheduled job activates the system's disk defragmenter. Were the situation different, you might sit and watch it for a while, but today, you just don't have that kind of time. It's soaking up valuable system resources that are needed elsewhere, and so the only option is to help it finish its task as soon as possible. The disk in question consists of a 128x128 grid; each square of the grid is either free or used. On this disk, the state of the grid is tracked by the bits in a sequence of knot hashes. A total of 128 knot hashes are calculated, each corresponding to a single row in the grid; each hash contains 128 bits which correspond to individual grid squares. Each bit of a hash indicates whether that square is free (0) or used (1). The hash inputs are a key string (your puzzle input), a dash, and a number from 0 to 127 corresponding to the row. For example, if your key string were flqrgnkx, then the first row would be given by the bits of the knot hash of flqrgnkx-0, the second row from the bits of the knot hash of flqrgnkx-1, and so on until the last row, flqrgnkx-127. The output of a knot hash is traditionally represented by 32 hexadecimal digits; each of these digits correspond to 4 bits, for a total of 4 * 32 = 128 bits. To convert to bits, turn each hexadecimal digit to its equivalent binary value, high-bit first: 0 becomes 0000, 1 becomes 0001, e becomes 1110, f becomes 1111, and so on; a hash that begins with a0c2017... in hexadecimal would begin with 10100000110000100000000101110000... in binary. Continuing this process, the first 8 rows and columns for key flqrgnkx appear as follows, using # to denote used squares, and . to denote free ones: ##.#.#..--> .#.#.#.# ....#.#. #.#.##.# .##.#... ##..#..# .#...#.. ##.#.##.--> | | V V In this example, 8108 squares are used across the entire 128x128 grid. Given your actual key string, how many squares are used? Your puzzle answer was 8216. --- Part Two --- Now, all the defragmenter needs to know is the number of regions. A region is a group of used squares that are all adjacent, not including diagonals. Every used square is in exactly one region: lone used squares form their own isolated regions, while several adjacent squares all count as a single region. In the example above, the following nine regions are visible, each marked with a distinct digit: 11.2.3..--> .1.2.3.4 ....5.6. 7.8.55.9 .88.5... 88..5..8 .8...8.. 88.8.88.--> | | V V Of particular interest is the region marked 8; while it does not appear contiguous in this small view, all of the squares marked 8 are connected when considering the whole 128x128 grid. In total, in this example, 1242 regions are present. How many regions are present given your key string?
216
--- Day 20: Infinite Elves and Infinite Houses --- To keep the Elves busy, Santa has them deliver some presents by hand, door-to-door. He sends them down a street with infinite houses numbered sequentially: 1, 2, 3, 4, 5, and so on. Each Elf is assigned a number, too, and delivers presents to houses based on that number: The first Elf (number 1) delivers presents to every house: 1, 2, 3, 4, 5, .... The second Elf (number 2) delivers presents to every second house: 2, 4, 6, 8, 10, .... Elf number 3 delivers presents to every third house: 3, 6, 9, 12, 15, .... There are infinitely many Elves, numbered starting with 1. Each Elf delivers presents equal to ten times his or her number at each house. So, the first nine houses on the street end up like this: House 1 got 10 presents. House 2 got 30 presents. House 3 got 40 presents. House 4 got 70 presents. House 5 got 60 presents. House 6 got 120 presents. House 7 got 80 presents. House 8 got 150 presents. House 9 got 130 presents. The first house gets 10 presents: it is visited only by Elf 1, which delivers 1 * 10 = 10 presents. The fourth house gets 70 presents, because it is visited by Elves 1, 2, and 4, for a total of 10 + 20 + 40 = 70 presents. What is the lowest house number of the house to get at least as many presents as the number in your puzzle input?
217
--- Day 18: Many-Worlds Interpretation --- As you approach Neptune, a planetary security system detects you and activates a giant tractor beam on Triton! You have no choice but to land. A scan of the local area reveals only one interesting feature: a massive underground vault. You generate a map of the tunnels (your puzzle input). The tunnels are too narrow to move diagonally. Only one entrance (marked @) is present among the open passages (marked .) and stone walls (#), but you also detect an assortment of keys (shown as lowercase letters) and doors (shown as uppercase letters). Keys of a given letter open the door of the same letter: a opens A, b opens B, and so on. You aren't sure which key you need to disable the tractor beam, so you'll need to collect all of them. For example, suppose you have the following map: ######### #[email protected]# ######### Starting from the entrance (@), you can only access a large door (A) and a key (a). Moving toward the door doesn't help you, but you can move 2 steps to collect the key, unlocking A in the process: ######### #b.....@# ######### Then, you can move 6 steps to collect the only other key, b: ######### #@......# ######### So, collecting every key took a total of 8 steps. Here is a larger example: ######################## #[email protected].# ######################.# #d.....................# ######################## The only reasonable move is to take key a and unlock door A: ######################## #[email protected].# ######################.# #d.....................# ######################## Then, do the same with key b: ######################## #[email protected].# ######################.# #d.....................# ######################## ...and the same with key c: ######################## #f.D.E.e.............@.# ######################.# #d.....................# ######################## Now, you have a choice between keys d and e. While key e is closer, collecting it now would be slower in the long run than collecting key d first, so that's the best choice: ######################## #f...E.e...............# ######################.# #@.....................# ######################## Finally, collect key e to unlock door E, then collect key f, taking a grand total of 86 steps. Here are a few more examples: ######################## #...............b.C.D.f# #.###################### #[email protected]# ######################## Shortest path is 132 steps: b, a, c, d, f, e, g ################# #i.G..c...e..H.p# ########.######## #j.A..b...f..D.o# ########@######## #k.E..a...g..B.n# ########.######## #l.F..d...h..C.m# ################# Shortest paths are 136 steps; one is: a, f, b, j, g, n, h, d, l, o, e, p, c, i, k, m ######################## #@..............ac.GI.b# ###d#e#f################ ###A#B#C################ ###g#h#i################ ######################## Shortest paths are 81 steps; one is: a, c, f, i, d, g, b, e, h How many steps is the shortest path that collects all of the keys?
218
--- Day 10: Adapter Array --- Patched into the aircraft's data port, you discover weather forecasts of a massive tropical storm. Before you can figure out whether it will impact your vacation plans, however, your device suddenly turns off! Its battery is dead. You'll need to plug it in. There's only one problem: the charging outlet near your seat produces the wrong number of jolts. Always prepared, you make a list of all of the joltage adapters in your bag. Each of your joltage adapters is rated for a specific output joltage (your puzzle input). Any given adapter can take an input 1, 2, or 3 jolts lower than its rating and still produce its rated output joltage. In addition, your device has a built-in joltage adapter rated for 3 jolts higher than the highest-rated adapter in your bag. (If your adapter list were 3, 9, and 6, your device's built-in adapter would be rated for 12 jolts.) Treat the charging outlet near your seat as having an effective joltage rating of 0. Since you have some time to kill, you might as well test all of your adapters. Wouldn't want to get to your resort and realize you can't even charge your device! If you use every adapter in your bag at once, what is the distribution of joltage differences between the charging outlet, the adapters, and your device? For example, suppose that in your bag, you have adapters with the following joltage ratings: 16 10 15 5 1 11 7 19 6 12 4 With these adapters, your device's built-in joltage adapter would be rated for 19 + 3 = 22 jolts, 3 higher than the highest-rated adapter. Because adapters can only connect to a source 1-3 jolts lower than its rating, in order to use every adapter, you'd need to choose them like this: The charging outlet has an effective rating of 0 jolts, so the only adapters that could connect to it directly would need to have a joltage rating of 1, 2, or 3 jolts. Of these, only one you have is an adapter rated 1 jolt (difference of 1). From your 1-jolt rated adapter, the only choice is your 4-jolt rated adapter (difference of 3). From the 4-jolt rated adapter, the adapters rated 5, 6, or 7 are valid choices. However, in order to not skip any adapters, you have to pick the adapter rated 5 jolts (difference of 1). Similarly, the next choices would need to be the adapter rated 6 and then the adapter rated 7 (with difference of 1 and 1). The only adapter that works with the 7-jolt rated adapter is the one rated 10 jolts (difference of 3). From 10, the choices are 11 or 12; choose 11 (difference of 1) and then 12 (difference of 1). After 12, only valid adapter has a rating of 15 (difference of 3), then 16 (difference of 1), then 19 (difference of 3). Finally, your device's built-in adapter is always 3 higher than the highest adapter, so its rating is 22 jolts (always a difference of 3). In this example, when using every adapter, there are 7 differences of 1 jolt and 5 differences of 3 jolts. Here is a larger example: 28 33 18 42 31 14 46 20 48 47 24 23 49 45 19 38 39 11 1 32 25 35 8 17 7 9 4 2 34 10 3 In this larger example, in a chain that uses all of the adapters, there are 22 differences of 1 jolt and 10 differences of 3 jolts. Find a chain that uses all of your adapters to connect the charging outlet to your device's built-in adapter and count the joltage differences between the charging outlet, the adapters, and your device. What is the number of 1-jolt differences multiplied by the number of 3-jolt differences? Your puzzle answer was 2812. --- Part Two --- To completely determine whether you have enough adapters, you'll need to figure out how many different ways they can be arranged. Every arrangement needs to connect the charging outlet to your device. The previous rules about when adapters can successfully connect still apply. The first example above (the one that starts with 16, 10, 15) supports the following arrangements: (0), 1, 4, 5, 6, 7, 10, 11, 12, 15, 16, 19, (22) (0), 1, 4, 5, 6, 7, 10, 12, 15, 16, 19, (22) (0), 1, 4, 5, 7, 10, 11, 12, 15, 16, 19, (22) (0), 1, 4, 5, 7, 10, 12, 15, 16, 19, (22) (0), 1, 4, 6, 7, 10, 11, 12, 15, 16, 19, (22) (0), 1, 4, 6, 7, 10, 12, 15, 16, 19, (22) (0), 1, 4, 7, 10, 11, 12, 15, 16, 19, (22) (0), 1, 4, 7, 10, 12, 15, 16, 19, (22) (The charging outlet and your device's built-in adapter are shown in parentheses.) Given the adapters from the first example, the total number of arrangements that connect the charging outlet to your device is 8. The second example above (the one that starts with 28, 33, 18) has many arrangements. Here are a few: (0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31, 32, 33, 34, 35, 38, 39, 42, 45, 46, 47, 48, 49, (52) (0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31, 32, 33, 34, 35, 38, 39, 42, 45, 46, 47, 49, (52) (0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31, 32, 33, 34, 35, 38, 39, 42, 45, 46, 48, 49, (52) (0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31, 32, 33, 34, 35, 38, 39, 42, 45, 46, 49, (52) (0), 1, 2, 3, 4, 7, 8, 9, 10, 11, 14, 17, 18, 19, 20, 23, 24, 25, 28, 31, 32, 33, 34, 35, 38, 39, 42, 45, 47, 48, 49, (52) (0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45, 46, 48, 49, (52) (0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45, 46, 49, (52) (0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45, 47, 48, 49, (52) (0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45, 47, 49, (52) (0), 3, 4, 7, 10, 11, 14, 17, 20, 23, 25, 28, 31, 34, 35, 38, 39, 42, 45, 48, 49, (52) In total, this set of adapters can connect the charging outlet to your device in 19208 distinct arrangements. You glance back down at your bag and try to remember why you brought so many adapters; there must be more than a trillion valid ways to arrange them! Surely, there must be an efficient way to count the arrangements. What is the total number of distinct ways you can arrange the adapters to connect the charging outlet to your device?
219
--- Day 5: If You Give A Seed A Fertilizer --- You take the boat and find the gardener right where you were told he would be: managing a giant "garden" that looks more to you like a farm. "A water source? Island Island is the water source!" You point out that Snow Island isn't receiving any water. "Oh, we had to stop the water because we ran out of sand to filter it with! Can't make snow with dirty water. Don't worry, I'm sure we'll get more sand soon; we only turned off the water a few days... weeks... oh no." His face sinks into a look of horrified realization. "I've been so busy making sure everyone here has food that I completely forgot to check why we stopped getting more sand! There's a ferry leaving soon that is headed over in that direction - it's much faster than your boat. Could you please go check it out?" You barely have time to agree to this request when he brings up another. "While you wait for the ferry, maybe you can help us with our food production problem. The latest Island Island Almanac just arrived and we're having trouble making sense of it." The almanac (your puzzle input) lists all of the seeds that need to be planted. It also lists what type of soil to use with each kind of seed, what type of fertilizer to use with each kind of soil, what type of water to use with each kind of fertilizer, and so on. Every type of seed, soil, fertilizer and so on is identified with a number, but numbers are reused by each category - that is, soil 123 and fertilizer 123 aren't necessarily related to each other. For example: seeds: 79 14 55 13 seed-to-soil map: 50 98 2 52 50 48 soil-to-fertilizer map: 0 15 37 37 52 2 39 0 15 fertilizer-to-water map: 49 53 8 0 11 42 42 0 7 57 7 4 water-to-light map: 88 18 7 18 25 70 light-to-temperature map: 45 77 23 81 45 19 68 64 13 temperature-to-humidity map: 0 69 1 1 0 69 humidity-to-location map: 60 56 37 56 93 4 The almanac starts by listing which seeds need to be planted: seeds 79, 14, 55, and 13. The rest of the almanac contains a list of maps which describe how to convert numbers from a source category into numbers in a destination category. That is, the section that starts with seed-to-soil map: describes how to convert a seed number (the source) to a soil number (the destination). This lets the gardener and his team know which soil to use with which seeds, which water to use with which fertilizer, and so on. Rather than list every source number and its corresponding destination number one by one, the maps describe entire ranges of numbers that can be converted. Each line within a map contains three numbers: the destination range start, the source range start, and the range length. Consider again the example seed-to-soil map: 50 98 2 52 50 48 The first line has a destination range start of 50, a source range start of 98, and a range length of 2. This line means that the source range starts at 98 and contains two values: 98 and 99. The destination range is the same length, but it starts at 50, so its two values are 50 and 51. With this information, you know that seed number 98 corresponds to soil number 50 and that seed number 99 corresponds to soil number 51. The second line means that the source range starts at 50 and contains 48 values: 50, 51, ..., 96, 97. This corresponds to a destination range starting at 52 and also containing 48 values: 52, 53, ..., 98, 99. So, seed number 53 corresponds to soil number 55. Any source numbers that aren't mapped correspond to the same destination number. So, seed number 10 corresponds to soil number 10. So, the entire list of seed numbers and their corresponding soil numbers looks like this: seed soil 0 0 1 1 ... ... 48 48 49 49 50 52 51 53 ... ... 96 98 97 99 98 50 99 51 With this map, you can look up the soil number required for each initial seed number: Seed number 79 corresponds to soil number 81. Seed number 14 corresponds to soil number 14. Seed number 55 corresponds to soil number 57. Seed number 13 corresponds to soil number 13. The gardener and his team want to get started as soon as possible, so they'd like to know the closest location that needs a seed. Using these maps, find the lowest location number that corresponds to any of the initial seeds. To do this, you'll need to convert each seed number through other categories until you can find its corresponding location number. In this example, the corresponding types are: Seed 79, soil 81, fertilizer 81, water 81, light 74, temperature 78, humidity 78, location 82. Seed 14, soil 14, fertilizer 53, water 49, light 42, temperature 42, humidity 43, location 43. Seed 55, soil 57, fertilizer 57, water 53, light 46, temperature 82, humidity 82, location 86. Seed 13, soil 13, fertilizer 52, water 41, light 34, temperature 34, humidity 35, location 35. So, the lowest location number in this example is 35. What is the lowest location number that corresponds to any of the initial seed numbers? Your puzzle answer was 173706076. --- Part Two --- Everyone will starve if you only plant such a small number of seeds. Re-reading the almanac, it looks like the seeds: line actually describes ranges of seed numbers. The values on the initial seeds: line come in pairs. Within each pair, the first value is the start of the range and the second value is the length of the range. So, in the first line of the example above: seeds: 79 14 55 13 This line describes two ranges of seed numbers to be planted in the garden. The first range starts with seed number 79 and contains 14 values: 79, 80, ..., 91, 92. The second range starts with seed number 55 and contains 13 values: 55, 56, ..., 66, 67. Now, rather than considering four seed numbers, you need to consider a total of 27 seed numbers. In the above example, the lowest location number can be obtained from seed number 82, which corresponds to soil 84, fertilizer 84, water 84, light 77, temperature 45, humidity 46, and location 46. So, the lowest location number is 46. Consider all of the initial seed numbers listed in the ranges on the first line of the almanac. What is the lowest location number that corresponds to any of the initial seed numbers?
220
--- Day 2: Password Philosophy --- Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan. The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with our computers; we can't log in!" You ask if you can take a look. Their password database seems to be a little corrupted: some of the passwords wouldn't have been allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen. To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set. For example, suppose you have the following list: 1-3 a: abcde 1-3 b: cdefg 2-9 c: ccccccccc Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times. In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies. How many passwords are valid according to their policies?
221
--- Day 18: Duet --- You discover a tablet containing some strange assembly code labeled simply "Duet". Rather than bother the sound card with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure out what the instructions mean on your own. It seems like the assembly is meant to operate on a set of registers that are each named with a single letter and that can each hold a single integer. You suppose each register should start with a value of 0. There aren't that many instructions, so it shouldn't be hard to figure out what they do. Here's what you determine: snd X plays a sound with a frequency equal to the value of X. set X Y sets register X to the value of Y. add X Y increases register X by the value of Y. mul X Y sets register X to the result of multiplying the value contained in register X by the value of Y. mod X Y sets register X to the remainder of dividing the value contained in register X by the value of Y (that is, it sets X to the result of X modulo Y). rcv X recovers the frequency of the last sound played, but only when the value of X is not zero. (If it is zero, the command does nothing.) jgz X Y jumps with an offset of the value of Y, but only if the value of X is greater than zero. (An offset of 2 skips the next instruction, an offset of -1 jumps to the previous instruction, and so on.) Many of the instructions can take either a register (a single letter) or a number. The value of a register is the integer it contains; the value of a number is that number. After each jump instruction, the program continues with the instruction to which the jump jumped. After any other instruction, the program continues with the next instruction. Continuing (or jumping) off either end of the program terminates it. For example: set a 1 add a 2 mul a a mod a 5 snd a set a 0 rcv a jgz a -1 set a 1 jgz a -2 The first four instructions set a to 1, add 2 to it, square it, and then set it to itself modulo 5, resulting in a value of 4. Then, a sound with frequency 4 (the value of a) is played. After that, a is set to 0, causing the subsequent rcv and jgz instructions to both be skipped (rcv because a is 0, and jgz because a is not greater than 0). Finally, a is set to 1, causing the next jgz instruction to activate, jumping back two instructions to another jump, which jumps again to the rcv, which ultimately triggers the recover operation. At the time the recover operation is executed, the frequency of the last sound played is 4. What is the value of the recovered frequency (the value of the most recently played sound) the first time a rcv instruction is executed with a non-zero value? Your puzzle answer was 3423. --- Part Two --- As you congratulate yourself for a job well done, you notice that the documentation has been on the back of the tablet this entire time. While you actually got most of the instructions correct, there are a few key differences. This assembly code isn't about sound at all - it's meant to be run twice at the same time. Each running copy of the program has its own set of registers and follows the code independently - in fact, the programs don't even necessarily run at the same speed. To coordinate, they use the send (snd) and receive (rcv) instructions: snd X sends the value of X to the other program. These values wait in a queue until that program is ready to receive them. Each program has its own message queue, so a program can never receive a message it sent. rcv X receives the next value and stores it in register X. If no values are in the queue, the program waits for a value to be sent to it. Programs do not continue to the next instruction until they have received a value. Values are received in the order they are sent. Each program also has its own program ID (one 0 and the other 1); the register p should begin with this value. For example: snd 1 snd 2 snd p rcv a rcv b rcv c rcv d Both programs begin by sending three values to the other. Program 0 sends 1, 2, 0; program 1 sends 1, 2, 1. Then, each program receives a value (both 1) and stores it in a, receives another value (both 2) and stores it in b, and then each receives the program ID of the other program (program 0 receives 1; program 1 receives 0) and stores it in c. Each program now sees a different value in its own copy of register c. Finally, both programs try to rcv a fourth time, but no data is waiting for either of them, and they reach a deadlock. When this happens, both programs terminate. It should be noted that it would be equally valid for the programs to run at different speeds; for example, program 0 might have sent all three values and then stopped at the first rcv before program 1 executed even its first instruction. Once both of your programs have terminated (regardless of what caused them to do so), how many times did program 1 send a value?
222
--- Day 2: Inventory Management System --- You stop falling through time, catch your breath, and check the screen on the device. "Destination reached. Current Year: 1518. Current Location: North Pole Utility Closet 83N10." You made it! Now, to find those anomalies. Outside the utility closet, you hear footsteps and a voice. "...I'm not sure either. But now that so many people have chimneys, maybe he could sneak in that way?" Another voice responds, "Actually, we've been working on a new kind of suit that would let him fit through tight spaces like that. But, I heard that a few days ago, they lost the prototype fabric, the design plans, everything! Nobody on the team can even seem to remember important details of the project!" "Wouldn't they have had enough fabric to fill several boxes in the warehouse? They'd be stored together, so the box IDs should be similar. Too bad it would take forever to search the warehouse for two similar box IDs..." They walk too far away to hear any more. Late at night, you sneak to the warehouse - who knows what kinds of paradoxes you could cause if you were discovered - and use your fancy wrist device to quickly scan every box and produce a list of the likely candidates (your puzzle input). To make sure you didn't miss any, you scan the likely candidate boxes again, counting the number that have an ID containing exactly two of any letter and then separately counting those with exactly three of any letter. You can multiply those two counts together to get a rudimentary checksum and compare it to what your device predicts. For example, if you see the following box IDs: abcdef contains no letters that appear exactly two or three times. bababc contains two a and three b, so it counts for both. abbcde contains two b, but no letter appears exactly three times. abcccd contains three c, but no letter appears exactly two times. aabcdd contains two a and two d, but it only counts once. abcdee contains two e. ababab contains three a and three b, but it only counts once. Of these box IDs, four of them contain a letter which appears exactly twice, and three of them contain a letter which appears exactly three times. Multiplying these together produces a checksum of 4 * 3 = 12. What is the checksum for your list of box IDs?
223
--- Day 25: Snowverload --- Still somehow without snow, you go to the last place you haven't checked: the center of Snow Island, directly below the waterfall. Here, someone has clearly been trying to fix the problem. Scattered everywhere are hundreds of weather machines, almanacs, communication modules, hoof prints, machine parts, mirrors, lenses, and so on. Somehow, everything has been wired together into a massive snow-producing apparatus, but nothing seems to be running. You check a tiny screen on one of the communication modules: Error 2023. It doesn't say what Error 2023 means, but it does have the phone number for a support line printed on it. "Hi, you've reached Weather Machines And So On, Inc. How can I help you?" You explain the situation. "Error 2023, you say? Why, that's a power overload error, of course! It means you have too many components plugged in. Try unplugging some components and--" You explain that there are hundreds of components here and you're in a bit of a hurry. "Well, let's see how bad it is; do you see a big red reset button somewhere? It should be on its own module. If you push it, it probably won't fix anything, but it'll report how overloaded things are." After a minute or two, you find the reset button; it's so big that it takes two hands just to get enough leverage to push it. Its screen then displays: SYSTEM OVERLOAD! Connected components would require power equal to at least 100 stars! "Wait, how many components did you say are plugged in? With that much equipment, you could produce snow for an entire--" You disconnect the call. You have nowhere near that many stars - you need to find a way to disconnect at least half of the equipment here, but it's already Christmas! You only have time to disconnect three wires. Fortunately, someone left a wiring diagram (your puzzle input) that shows how the components are connected. For example: jqt: rhn xhk nvd rsh: frs pzl lsr xhk: hfx cmg: qnr nvd lhk bvb rhn: xhk bvb hfx bvb: xhk hfx pzl: lsr hfx nvd qnr: nvd ntq: jqt hfx bvb xhk nvd: lhk lsr: lhk rzs: qnr cmg lsr rsh frs: qnr lhk lsr Each line shows the name of a component, a colon, and then a list of other components to which that component is connected. Connections aren't directional; abc: xyz and xyz: abc both represent the same configuration. Each connection between two components is represented only once, so some components might only ever appear on the left or right side of a colon. In this example, if you disconnect the wire between hfx/pzl, the wire between bvb/cmg, and the wire between nvd/jqt, you will divide the components into two separate, disconnected groups: 9 components: cmg, frs, lhk, lsr, nvd, pzl, qnr, rsh, and rzs. 6 components: bvb, hfx, jqt, ntq, rhn, and xhk. Multiplying the sizes of these groups together produces 54. Find the three wires you need to disconnect in order to divide the components into two separate groups. What do you get if you multiply the sizes of these two groups together?
224
--- Day 23: Crab Cups --- The small crab challenges you to a game! The crab is going to mix up some cups, and you have to predict where they'll end up. The cups will be arranged in a circle and labeled clockwise (your puzzle input). For example, if your labeling were 32415, there would be five cups in the circle; going clockwise around the circle from the first cup, the cups would be labeled 3, 2, 4, 1, 5, and then back to 3 again. Before the crab starts, it will designate the first cup in your list as the current cup. The crab is then going to do 100 moves. Each move, the crab does the following actions: The crab picks up the three cups that are immediately clockwise of the current cup. They are removed from the circle; cup spacing is adjusted as necessary to maintain the circle. The crab selects a destination cup: the cup with a label equal to the current cup's label minus one. If this would select one of the cups that was just picked up, the crab will keep subtracting one until it finds a cup that wasn't just picked up. If at any point in this process the value goes below the lowest value on any cup's label, it wraps around to the highest value on any cup's label instead. The crab places the cups it just picked up so that they are immediately clockwise of the destination cup. They keep the same order as when they were picked up. The crab selects a new current cup: the cup which is immediately clockwise of the current cup. For example, suppose your cup labeling were 389125467. If the crab were to do merely 10 moves, the following changes would occur: -- move 1 -- cups: (3) 8 9 1 2 5 4 6 7 pick up: 8, 9, 1 destination: 2 -- move 2 -- cups: 3 (2) 8 9 1 5 4 6 7 pick up: 8, 9, 1 destination: 7 -- move 3 -- cups: 3 2 (5) 4 6 7 8 9 1 pick up: 4, 6, 7 destination: 3 -- move 4 -- cups: 7 2 5 (8) 9 1 3 4 6 pick up: 9, 1, 3 destination: 7 -- move 5 -- cups: 3 2 5 8 (4) 6 7 9 1 pick up: 6, 7, 9 destination: 3 -- move 6 -- cups: 9 2 5 8 4 (1) 3 6 7 pick up: 3, 6, 7 destination: 9 -- move 7 -- cups: 7 2 5 8 4 1 (9) 3 6 pick up: 3, 6, 7 destination: 8 -- move 8 -- cups: 8 3 6 7 4 1 9 (2) 5 pick up: 5, 8, 3 destination: 1 -- move 9 -- cups: 7 4 1 5 8 3 9 2 (6) pick up: 7, 4, 1 destination: 5 -- move 10 -- cups: (5) 7 4 1 8 3 9 2 6 pick up: 7, 4, 1 destination: 3 -- final -- cups: 5 (8) 3 7 4 1 9 2 6 In the above example, the cups' values are the labels as they appear moving clockwise around the circle; the current cup is marked with ( ). After the crab is done, what order will the cups be in? Starting after the cup labeled 1, collect the other cups' labels clockwise into a single string with no extra characters; each number except 1 should appear exactly once. In the above example, after 10 moves, the cups clockwise from 1 are labeled 9, 2, 6, 5, and so on, producing 92658374. If the crab were to complete all 100 moves, the order after cup 1 would be 67384529. Using your labeling, simulate 100 moves. What are the labels on the cups after cup 1?
225
--- Day 15: Chiton --- You've almost reached the exit of the cave, but the walls are getting closer together. Your submarine can barely still fit, though; the main problem is that the walls of the cave are covered in chitons, and it would be best not to bump any of them. The cavern is large, but has a very low ceiling, restricting your motion to two dimensions. The shape of the cavern resembles a square; a quick scan of chiton density produces a map of risk level throughout the cave (your puzzle input). For example: 1163751742 1381373672 2136511328 3694931569 7463417111 1319128137 1359912421 3125421639 1293138521 2311944581 You start in the top left position, your destination is the bottom right position, and you cannot move diagonally. The number at each position is its risk level; to determine the total risk of an entire path, add up the risk levels of each position you enter (that is, don't count the risk level of your starting position unless you enter it; leaving it adds no risk to your total). Your goal is to find a path with the lowest total risk. In this example, a path with the lowest total risk is highlighted here: 1163751742 1381373672 2136511328 3694931569 7463417111 1319128137 1359912421 3125421639 1293138521 2311944581 The total risk of this path is 40 (the starting position is never entered, so its risk is not counted). What is the lowest total risk of any path from the top left to the bottom right?
226
--- Day 2: Cube Conundrum --- You're launched high into the atmosphere! The apex of your trajectory just barely reaches the surface of a large island floating in the sky. You gently land in a fluffy pile of leaves. It's quite cold, but you don't see much snow. An Elf runs over to greet you. The Elf explains that you've arrived at Snow Island and apologizes for the lack of snow. He'll be happy to explain the situation, but it's a bit of a walk, so you have some time. They don't get many visitors up here; would you like to play a game in the meantime? As you walk, the Elf shows you a small bag and some cubes which are either red, green, or blue. Each time you play this game, he will hide a secret number of cubes of each color in the bag, and your goal is to figure out information about the number of cubes. To get information, once a bag has been loaded with cubes, the Elf will reach into the bag, grab a handful of random cubes, show them to you, and then put them back in the bag. He'll do this a few times per game. You play several games and record the information from each game (your puzzle input). Each game is listed with its ID number (like the 11 in Game 11: ...) followed by a semicolon-separated list of subsets of cubes that were revealed from the bag (like 3 red, 5 green, 4 blue). For example, the record of a few games might look like this: Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green In game 1, three sets of cubes are revealed from the bag (and then put back again). The first set is 3 blue cubes and 4 red cubes; the second set is 1 red cube, 2 green cubes, and 6 blue cubes; the third set is only 2 green cubes. The Elf would first like to know which games would have been possible if the bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes? In the example above, games 1, 2, and 5 would have been possible if the bag had been loaded with that configuration. However, game 3 would have been impossible because at one point the Elf showed you 20 red cubes at once; similarly, game 4 would also have been impossible because the Elf showed you 15 blue cubes at once. If you add up the IDs of the games that would have been possible, you get 8. Determine which games would have been possible if the bag had been loaded with only 12 red cubes, 13 green cubes, and 14 blue cubes. What is the sum of the IDs of those games?
227
--- Day 1: Chronal Calibration --- "We've detected some temporal anomalies," one of Santa's Elves at the Temporal Anomaly Research and Detection Instrument Station tells you. She sounded pretty worried when she called you down here. "At 500-year intervals into the past, someone has been changing Santa's history!" "The good news is that the changes won't propagate to our time stream for another 25 days, and we have a device" - she attaches something to your wrist - "that will let you fix the changes with no such propagation delay. It's configured to send you 500 years further into the past every few days; that was the best we could do on such short notice." "The bad news is that we are detecting roughly fifty anomalies throughout time; the device will indicate fixed anomalies with stars. The other bad news is that we only have one device and you're the best person for the job! Good lu--" She taps a button on the device and you suddenly feel like you're falling. To save Christmas, you need to get all fifty stars by December 25th. Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! After feeling like you've been falling for a few minutes, you look at the device's tiny screen. "Error: Device must be calibrated before first use. Frequency drift detected. Cannot maintain destination lock." Below the message, the device shows a sequence of changes in frequency (your puzzle input). A value like +6 means the current frequency increases by 6; a value like -3 means the current frequency decreases by 3. For example, if the device displays frequency changes of +1, -2, +3, +1, then starting from a frequency of zero, the following changes would occur: Current frequency 0, change of +1; resulting frequency 1. Current frequency 1, change of -2; resulting frequency -1. Current frequency -1, change of +3; resulting frequency 2. Current frequency 2, change of +1; resulting frequency 3. In this example, the resulting frequency is 3. Here are other example situations: +1, +1, +1 results in 3 +1, +1, -2 results in 0 -1, -2, -3 results in -6 Starting with a frequency of zero, what is the resulting frequency after all of the changes in frequency have been applied? Your puzzle answer was 406. --- Part Two --- You notice that the device repeats the same frequency change list over and over. To calibrate the device, you need to find the first frequency it reaches twice. For example, using the same list of changes above, the device would loop as follows: Current frequency 0, change of +1; resulting frequency 1. Current frequency 1, change of -2; resulting frequency -1. Current frequency -1, change of +3; resulting frequency 2. Current frequency 2, change of +1; resulting frequency 3. (At this point, the device continues from the start of the list.) Current frequency 3, change of +1; resulting frequency 4. Current frequency 4, change of -2; resulting frequency 2, which has already been seen. In this example, the first frequency reached twice is 2. Note that your device might need to repeat its list of frequency changes many times before a duplicate frequency is found, and that duplicates might be found while in the middle of processing the list. Here are other examples: +1, -1 first reaches 0 twice. +3, +3, +4, -2, -4 first reaches 10 twice. -6, +3, +8, +5, -6 first reaches 5 twice. +7, +7, -2, -7, -4 first reaches 14 twice. What is the first frequency your device reaches twice?
228
--- Day 13: A Maze of Twisty Little Cubicles --- You arrive at the first floor of this new building to discover a much less welcoming environment than the shiny atrium of the last one. Instead, you are in a maze of twisty little cubicles, all alike. Every location in this area is addressed by a pair of non-negative integers (x,y). Each such coordinate is either a wall or an open space. You can't move diagonally. The cube maze starts at 0,0 and seems to extend infinitely toward positive x and y; negative values are invalid, as they represent a location outside the building. You are in a small waiting area at 1,1. While it seems chaotic, a nearby morale-boosting poster explains, the layout is actually quite logical. You can determine whether a given x,y coordinate will be a wall or an open space using a simple system: Find x*x + 3*x + 2*x*y + y + y*y. Add the office designer's favorite number (your puzzle input). Find the binary representation of that sum; count the number of bits that are 1. If the number of bits that are 1 is even, it's an open space. If the number of bits that are 1 is odd, it's a wall. For example, if the office designer's favorite number were 10, drawing walls as # and open spaces as ., the corner of the building containing 0,0 would look like this: 0123456789 0 .#.####.## 1 ..#..#...# 2 #....##... 3 ###.#.###. 4 .##..#..#. 5 ..##....#. 6 #...##.### Now, suppose you wanted to reach 7,4. The shortest route you could take is marked as O: 0123456789 0 .#.####.## 1 .O#..#...# 2 #OOO.##... 3 ###O#.###. 4 .##OO#OO#. 5 ..##OOO.#. 6 #...##.### Thus, reaching 7,4 would take a minimum of 11 steps (starting from your current location, 1,1). What is the fewest number of steps required for you to reach 31,39?
229
--- Day 6: Probably a Fire Hazard --- Because your neighbors keep defeating you in the holiday house decorating contest year after year, you've decided to deploy one million lights in a 1000x1000 grid. Furthermore, because you've been especially nice this year, Santa has mailed you instructions on how to display the ideal lighting configuration. Lights in your grid are numbered from 0 to 999 in each direction; the lights at each corner are at 0,0, 0,999, 999,999, and 999,0. The instructions include whether to turn on, turn off, or toggle various inclusive ranges given as coordinate pairs. Each coordinate pair represents opposite corners of a rectangle, inclusive; a coordinate pair like 0,0 through 2,2 therefore refers to 9 lights in a 3x3 square. The lights all start turned off. To defeat your neighbors this year, all you have to do is set up your lights by doing the instructions Santa sent you in order. For example: turn on 0,0 through 999,999 would turn on (or leave on) every light. toggle 0,0 through 999,0 would toggle the first line of 1000 lights, turning off the ones that were on, and turning on the ones that were off. turn off 499,499 through 500,500 would turn off (or leave off) the middle four lights. After following the instructions, how many lights are lit?
230
--- Day 2: Bathroom Security --- You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code. "In order to improve security," the document you find says, "bathroom codes will no longer be written down. Instead, please memorize and follow the procedure below to access the bathrooms." The document goes on to explain that each button to be pressed can be found by starting on the previous button and moving to adjacent buttons on the keypad: U moves up, D moves down, L moves left, and R moves right. Each line of instructions corresponds to one button, starting at the previous button (or, for the first line, the "5" button); press whatever button you're on at the end of each line. If a move doesn't lead to a button, ignore it. You can't hold it much longer, so you decide to figure out the code as you walk to the bathroom. You picture a keypad like this: 1 2 3 4 5 6 7 8 9 Suppose your instructions are: ULL RRDDD LURDL UUUUD You start at "5" and move up (to "2"), left (to "1"), and left (you can't, and stay on "1"), so the first button is 1. Starting from the previous button ("1"), you move right twice (to "3") and then down three times (stopping at "9" after two moves and ignoring the third), ending up with 9. Continuing from "9", you move left, up, right, down, and left, ending with 8. Finally, you move up four times (stopping at "2"), then down once, ending with 5. So, in this example, the bathroom code is 1985. Your puzzle input is the instructions from the document you found at the front desk. What is the bathroom code? Your puzzle answer was 12578. --- Part Two --- You finally arrive at the bathroom (it's a several minute walk from the lobby so visitors can behold the many fancy conference rooms and water coolers on this floor) and go to punch in the code. Much to your bladder's dismay, the keypad is not at all like you imagined it. Instead, you are confronted with the result of hundreds of man-hours of bathroom-keypad-design meetings: 1 2 3 4 5 6 7 8 9 A B C D You still start at "5" and stop when you're at an edge, but given the same instructions as above, the outcome is very different: You start at "5" and don't move at all (up and left are both edges), ending at 5. Continuing from "5", you move right twice and down three times (through "6", "7", "B", "D", "D"), ending at D. Then, from "D", you move five more times (through "D", "B", "C", "C", "B"), ending at B. Finally, after five more moves, you end at 3. So, given the actual keypad layout, the code would be 5DB3. Using the same instructions in your puzzle input, what is the correct bathroom code?
231
--- Day 4: Secure Container --- You arrive at the Venus fuel depot only to discover it's protected by a password. The Elves had written the password on a sticky note, but someone threw it out. However, they do remember a few key facts about the password: It is a six-digit number. The value is within the range given in your puzzle input. Two adjacent digits are the same (like 22 in 122345). Going from left to right, the digits never decrease; they only ever increase or stay the same (like 111123 or 135679). Other than the range rule, the following are true: 111111 meets these criteria (double 11, never decreases). 223450 does not meet these criteria (decreasing pair of digits 50). 123789 does not meet these criteria (no double). How many different passwords within the range given in your puzzle input meet these criteria?
232
--- Day 3: Rucksack Reorganization --- One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn't quite follow the packing instructions, and so a few items now need to be rearranged. Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack. The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items). The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment. For example, suppose you have the following list of contents from six rucksacks: vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw The first rucksack contains the items vJrwpWtwJgWrhcsFMMfFFhFp, which means its first compartment contains the items vJrwpWtwJgWr, while the second compartment contains the items hcsFMMfFFhFp. The only item type that appears in both compartments is lowercase p. The second rucksack's compartments contain jqHRNqRjqzjGDLGL and rsFMfFZSrLrFZsSL. The only item type that appears in both compartments is uppercase L. The third rucksack's compartments contain PmmdzqPrV and vPwwTWBwg; the only common item type is uppercase P. The fourth rucksack's compartments only share item type v. The fifth rucksack's compartments only share item type t. The sixth rucksack's compartments only share item type s. To help prioritize item rearrangement, every item type can be converted to a priority: Lowercase item types a through z have priorities 1 through 26. Uppercase item types A through Z have priorities 27 through 52. In the above example, the priority of the item type that appears in both compartments of each rucksack is 16 (p), 38 (L), 42 (P), 22 (v), 20 (t), and 19 (s); the sum of these is 157. Find the item type that appears in both compartments of each rucksack. What is the sum of the priorities of those item types? Your puzzle answer was 8233. --- Part Two --- As you finish identifying the misplaced items, the Elves come to you with another issue. For safety, the Elves are divided into groups of three. Every Elf carries a badge that identifies their group. For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves. That is, if a group's badge is item type B, then all three Elves will have item type B somewhere in their rucksack, and at most two of the Elves will be carrying any other item type. The problem is that someone forgot to put this year's updated authenticity sticker on the badges. All of the badges need to be pulled out of the rucksacks so the new authenticity stickers can be attached. Additionally, nobody wrote down which item type corresponds to each group's badges. The only way to tell which item type is the right one is by finding the one item type that is common between all three Elves in each group. Every set of three lines in your list corresponds to a single group, but each group can have a different badge item type. So, in the above example, the first group's rucksacks are the first three lines: vJrwpWtwJgWrhcsFMMfFFhFp jqHRNqRjqzjGDLGLrsFMfFZSrLrFZsSL PmmdzqPrVvPwwTWBwg And the second group's rucksacks are the next three lines: wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn ttgJtRGJQctTZtZT CrZsJsPPZsGzwwsLwLmpwMDw In the first group, the only item type that appears in all three rucksacks is lowercase r; this must be their badges. In the second group, their badge item type must be Z. Priorities for these items must still be found to organize the sticker attachment efforts: here, they are 18 (r) for the first group and 52 (Z) for the second group. The sum of these is 70. Find the item type that corresponds to the badges of each three-Elf group. What is the sum of the priorities of those item types?
233
--- Day 12: Passage Pathing --- With your submarine's subterranean subsystems subsisting suboptimally, the only way you're getting out of this cave anytime soon is by finding a path yourself. Not just a path - the only way to know if you've found the best path is to find all of them. Fortunately, the sensors are still mostly working, and so you build a rough map of the remaining caves (your puzzle input). For example: start-A start-b A-c A-b b-d A-end b-end This is a list of how all of the caves are connected. You start in the cave named start, and your destination is the cave named end. An entry like b-d means that cave b is connected to cave d - that is, you can move between them. So, the above cave system looks roughly like this: start / c--A-----b--d / end Your goal is to find the number of distinct paths that start at start, end at end, and don't visit small caves more than once. There are two types of caves: big caves (written in uppercase, like A) and small caves (written in lowercase, like b). It would be a waste of time to visit any small cave more than once, but big caves are large enough that it might be worth visiting them multiple times. So, all paths you find should visit small caves at most once, and can visit big caves any number of times. Given these rules, there are 10 paths through this example cave system: start,A,b,A,c,A,end start,A,b,A,end start,A,b,end start,A,c,A,b,A,end start,A,c,A,b,end start,A,c,A,end start,A,end start,b,A,c,A,end start,b,A,end start,b,end (Each line in the above list corresponds to a single path; the caves visited by that path are listed in the order they are visited and separated by commas.) Note that in this cave system, cave d is never visited by any path: to do so, cave b would need to be visited twice (once on the way to cave d and a second time when returning from cave d), and since cave b is small, this is not allowed. Here is a slightly larger example: dc-end HN-start start-kj dc-start dc-HN LN-dc HN-end kj-sa kj-HN kj-dc The 19 paths through it are as follows: start,HN,dc,HN,end start,HN,dc,HN,kj,HN,end start,HN,dc,end start,HN,dc,kj,HN,end start,HN,end start,HN,kj,HN,dc,HN,end start,HN,kj,HN,dc,end start,HN,kj,HN,end start,HN,kj,dc,HN,end start,HN,kj,dc,end start,dc,HN,end start,dc,HN,kj,HN,end start,dc,end start,dc,kj,HN,end start,kj,HN,dc,HN,end start,kj,HN,dc,end start,kj,HN,end start,kj,dc,HN,end start,kj,dc,end Finally, this even larger example has 226 paths through it: fs-end he-DX fs-he start-DX pj-DX end-zg zg-sl zg-pj pj-he RW-he fs-DX pj-RW zg-RW start-pj he-WI zg-he pj-fs start-RW How many paths through this cave system are there that visit small caves at most once? Your puzzle answer was 4011. --- Part Two --- After reviewing the available paths, you realize you might have time to visit a single small cave twice. Specifically, big caves can be visited any number of times, a single small cave can be visited at most twice, and the remaining small caves can be visited at most once. However, the caves named start and end can only be visited exactly once each: once you leave the start cave, you may not return to it, and once you reach the end cave, the path must end immediately. Now, the 36 possible paths through the first example above are: start,A,b,A,b,A,c,A,end start,A,b,A,b,A,end start,A,b,A,b,end start,A,b,A,c,A,b,A,end start,A,b,A,c,A,b,end start,A,b,A,c,A,c,A,end start,A,b,A,c,A,end start,A,b,A,end start,A,b,d,b,A,c,A,end start,A,b,d,b,A,end start,A,b,d,b,end start,A,b,end start,A,c,A,b,A,b,A,end start,A,c,A,b,A,b,end start,A,c,A,b,A,c,A,end start,A,c,A,b,A,end start,A,c,A,b,d,b,A,end start,A,c,A,b,d,b,end start,A,c,A,b,end start,A,c,A,c,A,b,A,end start,A,c,A,c,A,b,end start,A,c,A,c,A,end start,A,c,A,end start,A,end start,b,A,b,A,c,A,end start,b,A,b,A,end start,b,A,b,end start,b,A,c,A,b,A,end start,b,A,c,A,b,end start,b,A,c,A,c,A,end start,b,A,c,A,end start,b,A,end start,b,d,b,A,c,A,end start,b,d,b,A,end start,b,d,b,end start,b,end The slightly larger example above now has 103 paths through it, and the even larger example now has 3509 paths through it. Given these new rules, how many paths through this cave system are there?
234
--- Day 14: Parabolic Reflector Dish --- You reach the place where all of the mirrors were pointing: a massive parabolic reflector dish attached to the side of another large mountain. The dish is made up of many small mirrors, but while the mirrors themselves are roughly in the shape of a parabolic reflector dish, each individual mirror seems to be pointing in slightly the wrong direction. If the dish is meant to focus light, all it's doing right now is sending it in a vague direction. This system must be what provides the energy for the lava! If you focus the reflector dish, maybe you can go where it's pointing and use the light to fix the lava production. Upon closer inspection, the individual mirrors each appear to be connected via an elaborate system of ropes and pulleys to a large metal platform below the dish. The platform is covered in large rocks of various shapes. Depending on their position, the weight of the rocks deforms the platform, and the shape of the platform controls which ropes move and ultimately the focus of the dish. In short: if you move the rocks, you can focus the dish. The platform even has a control panel on the side that lets you tilt it in one of four directions! The rounded rocks (O) will roll when the platform is tilted, while the cube-shaped rocks (#) will stay in place. You note the positions of all of the empty spaces (.) and rocks (your puzzle input). For example: O....#.... O.OO#....# .....##... OO.#O....O .O.....O#. O.#..O.#.# ..O..#O..O .......O.. #....###.. #OO..#.... Start by tilting the lever so all of the rocks will slide north as far as they will go: OOOO.#.O.. OO..#....# OO..O##..O O..#.OO... ........#. ..#....#.# ..O..#.O.O ..O....... #....###.. #....#.... You notice that the support beams along the north side of the platform are damaged; to ensure the platform doesn't collapse, you should calculate the total load on the north support beams. The amount of load caused by a single rounded rock (O) is equal to the number of rows from the rock to the south edge of the platform, including the row the rock is on. (Cube-shaped rocks (#) don't contribute to load.) So, the amount of load caused by each rock in each row is as follows: OOOO.#.O.. 10 OO..#....# 9 OO..O##..O 8 O..#.OO... 7 ........#. 6 ..#....#.# 5 ..O..#.O.O 4 ..O....... 3 #....###.. 2 #....#.... 1 The total load is the sum of the load caused by all of the rounded rocks. In this example, the total load is 136. Tilt the platform so that the rounded rocks all roll north. Afterward, what is the total load on the north support beams? Your puzzle answer was 108759. --- Part Two --- The parabolic reflector dish deforms, but not in a way that focuses the beam. To do that, you'll need to move the rocks to the edges of the platform. Fortunately, a button on the side of the control panel labeled "spin cycle" attempts to do just that! Each cycle tilts the platform four times so that the rounded rocks roll north, then west, then south, then east. After each tilt, the rounded rocks roll as far as they can before the platform tilts in the next direction. After one cycle, the platform will have finished rolling the rounded rocks in those four directions in that order. Here's what happens in the example above after each of the first few cycles: After 1 cycle: .....#.... ....#...O# ...OO##... .OO#...... .....OOO#. .O#...O#.# ....O#.... ......OOOO #...O###.. #..OO#.... After 2 cycles: .....#.... ....#...O# .....##... ..O#...... .....OOO#. .O#...O#.# ....O#...O .......OOO #..OO###.. #.OOO#...O After 3 cycles: .....#.... ....#...O# .....##... ..O#...... .....OOO#. .O#...O#.# ....O#...O .......OOO #...O###.O #.OOO#...O This process should work if you leave it running long enough, but you're still worried about the north support beams. To make sure they'll survive for a while, you need to calculate the total load on the north support beams after 1000000000 cycles. In the above example, after 1000000000 cycles, the total load on the north support beams is 64. Run the spin cycle for 1000000000 cycles. Afterward, what is the total load on the north support beams?
235
--- Day 9: Encoding Error --- With your neighbor happily enjoying their video game, you turn your attention to an open data port on the little screen in the seat in front of you. Though the port is non-standard, you manage to connect it to your computer through the clever use of several paperclips. Upon connection, the port outputs a series of numbers (your puzzle input). The data appears to be encrypted with the eXchange-Masking Addition System (XMAS) which, conveniently for you, is an old cypher with an important weakness. XMAS starts by transmitting a preamble of 25 numbers. After that, each number you receive should be the sum of any two of the 25 immediately previous numbers. The two numbers will have different values, and there might be more than one such pair. For example, suppose your preamble consists of the numbers 1 through 25 in a random order. To be valid, the next number must be the sum of two of those numbers: 26 would be a valid next number, as it could be 1 plus 25 (or many other pairs, like 2 and 24). 49 would be a valid next number, as it is the sum of 24 and 25. 100 would not be valid; no two of the previous 25 numbers sum to 100. 50 would also not be valid; although 25 appears in the previous 25 numbers, the two numbers in the pair must be different. Suppose the 26th number is 45, and the first number (no longer an option, as it is more than 25 numbers ago) was 20. Now, for the next number to be valid, there needs to be some pair of numbers among 1-19, 21-25, or 45 that add up to it: 26 would still be a valid next number, as 1 and 25 are still within the previous 25 numbers. 65 would not be valid, as no two of the available numbers sum to it. 64 and 66 would both be valid, as they are the result of 19+45 and 21+45 respectively. Here is a larger example which only considers the previous 5 numbers (and has a preamble of length 5): 35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576 In this example, after the 5-number preamble, almost every number is the sum of two of the previous 5 numbers; the only number that does not follow this rule is 127. The first step of attacking the weakness in the XMAS data is to find the first number in the list (after the preamble) which is not the sum of two of the 25 numbers before it. What is the first number that does not have this property? Your puzzle answer was 14360655. --- Part Two --- The final step in breaking the XMAS encryption relies on the invalid number you just found: you must find a contiguous set of at least two numbers in your list which sum to the invalid number from step 1. Again consider the above example: 35 20 15 25 47 40 62 55 65 95 102 117 150 182 127 219 299 277 309 576 In this list, adding up all of the numbers from 15 through 40 produces the invalid number from step 1, 127. (Of course, the contiguous set of numbers in your actual list might be much longer.) To find the encryption weakness, add together the smallest and largest number in this contiguous range; in this example, these are 15 and 47, producing 62. What is the encryption weakness in your XMAS-encrypted list of numbers?
236
--- Day 8: Treetop Tree House --- The expedition comes across a peculiar patch of tall trees all planted carefully in a grid. The Elves explain that a previous expedition planted these trees as a reforestation effort. Now, they're curious if this would be a good location for a tree house. First, determine whether there is enough tree cover here to keep a tree house hidden. To do this, you need to count the number of trees that are visible from outside the grid when looking directly along a row or column. The Elves have already launched a quadcopter to generate a map with the height of each tree (your puzzle input). For example: 30373 25512 65332 33549 35390 Each tree is represented as a single digit whose value is its height, where 0 is the shortest and 9 is the tallest. A tree is visible if all of the other trees between it and an edge of the grid are shorter than it. Only consider trees in the same row or column; that is, only look up, down, left, or right from any given tree. All of the trees around the edge of the grid are visible - since they are already on the edge, there are no trees to block the view. In this example, that only leaves the interior nine trees to consider: The top-left 5 is visible from the left and top. (It isn't visible from the right or bottom since other trees of height 5 are in the way.) The top-middle 5 is visible from the top and right. The top-right 1 is not visible from any direction; for it to be visible, there would need to only be trees of height 0 between it and an edge. The left-middle 5 is visible, but only from the right. The center 3 is not visible from any direction; for it to be visible, there would need to be only trees of at most height 2 between it and an edge. The right-middle 3 is visible from the right. In the bottom row, the middle 5 is visible, but the 3 and 4 are not. With 16 trees visible on the edge and another 5 visible in the interior, a total of 21 trees are visible in this arrangement. Consider your map; how many trees are visible from outside the grid? Your puzzle answer was 1849. --- Part Two --- Content with the amount of tree cover available, the Elves just need to know the best spot to build their tree house: they would like to be able to see a lot of trees. To measure the viewing distance from a given tree, look up, down, left, and right from that tree; stop if you reach an edge or at the first tree that is the same height or taller than the tree under consideration. (If a tree is right on the edge, at least one of its viewing distances will be zero.) The Elves don't care about distant trees taller than those found by the rules above; the proposed tree house has large eaves to keep it dry, so they wouldn't be able to see higher than the tree house anyway. In the example above, consider the middle 5 in the second row: 30373 25512 65332 33549 35390 Looking up, its view is not blocked; it can see 1 tree (of height 3). Looking left, its view is blocked immediately; it can see only 1 tree (of height 5, right next to it). Looking right, its view is not blocked; it can see 2 trees. Looking down, its view is blocked eventually; it can see 2 trees (one of height 3, then the tree of height 5 that blocks its view). A tree's scenic score is found by multiplying together its viewing distance in each of the four directions. For this tree, this is 4 (found by multiplying 1 * 1 * 2 * 2). However, you can do even better: consider the tree of height 5 in the middle of the fourth row: 30373 25512 65332 33549 35390 Looking up, its view is blocked at 2 trees (by another tree with a height of 5). Looking left, its view is not blocked; it can see 2 trees. Looking down, its view is also not blocked; it can see 1 tree. Looking right, its view is blocked at 2 trees (by a massive tree of height 9). This tree's scenic score is 8 (2 * 2 * 1 * 2); this is the ideal spot for the tree house. Consider each tree on your map. What is the highest scenic score possible for any tree?
237
--- Day 2: I Was Told There Would Be No Math --- The elves are running low on wrapping paper, and so they need to submit an order for more. They have a list of the dimensions (length l, width w, and height h) of each present, and only want to order exactly as much as they need. Fortunately, every present is a box (a perfect right rectangular prism), which makes calculating the required wrapping paper for each gift a little easier: find the surface area of the box, which is 2*l*w + 2*w*h + 2*h*l. The elves also need a little extra paper for each present: the area of the smallest side. For example: A present with dimensions 2x3x4 requires 2*6 + 2*12 + 2*8 = 52 square feet of wrapping paper plus 6 square feet of slack, for a total of 58 square feet. A present with dimensions 1x1x10 requires 2*1 + 2*10 + 2*10 = 42 square feet of wrapping paper plus 1 square foot of slack, for a total of 43 square feet. All numbers in the elves' list are in feet. How many total square feet of wrapping paper should they order?
238
--- Day 23: Opening the Turing Lock --- Little Jane Marie just got her very first computer for Christmas from some unknown benefactor. It comes with instructions and an example program, but the computer itself seems to be malfunctioning. She's curious what the program does, and would like you to help her run it. The manual explains that the computer supports two registers and six instructions (truly, it goes on to remind the reader, a state-of-the-art technology). The registers are named a and b, can hold any non-negative integer, and begin with a value of 0. The instructions are as follows: hlf r sets register r to half its current value, then continues with the next instruction. tpl r sets register r to triple its current value, then continues with the next instruction. inc r increments register r, adding 1 to it, then continues with the next instruction. jmp offset is a jump; it continues with the instruction offset away relative to itself. jie r, offset is like jmp, but only jumps if register r is even ("jump if even"). jio r, offset is like jmp, but only jumps if register r is 1 ("jump if one", not odd). All three jump instructions work with an offset relative to that instruction. The offset is always written with a prefix + or - to indicate the direction of the jump (forward or backward, respectively). For example, jmp +1 would simply continue with the next instruction, while jmp +0 would continuously jump back to itself forever. The program exits when it tries to run an instruction beyond the ones defined. For example, this program sets a to 2, because the jio instruction causes it to skip the tpl instruction: inc a jio a, +2 tpl a inc a What is the value in register b when the program in your puzzle input is finished executing?
239
--- Day 16: Chronal Classification --- As you see the Elves defend their hot chocolate successfully, you go back to falling through time. This is going to become a problem. If you're ever going to return to your own time, you need to understand how this device on your wrist works. You have a little while before you reach your next destination, and with a bit of trial and error, you manage to pull up a programming manual on the device's tiny screen. According to the manual, the device has four registers (numbered 0 through 3) that can be manipulated by instructions containing one of 16 opcodes. The registers start with the value 0. Every instruction consists of four values: an opcode, two inputs (named A and B), and an output (named C), in that order. The opcode specifies the behavior of the instruction and how the inputs are interpreted. The output, C, is always treated as a register. In the opcode descriptions below, if something says "value A", it means to take the number given as A literally. (This is also called an "immediate" value.) If something says "register A", it means to use the number given as A to read from (or write to) the register with that number. So, if the opcode addi adds register A and value B, storing the result in register C, and the instruction addi 0 7 3 is encountered, it would add 7 to the value contained by register 0 and store the sum in register 3, never modifying registers 0, 1, or 2 in the process. Many opcodes are similar except for how they interpret their arguments. The opcodes fall into seven general categories: Addition: addr (add register) stores into register C the result of adding register A and register B. addi (add immediate) stores into register C the result of adding register A and value B. Multiplication: mulr (multiply register) stores into register C the result of multiplying register A and register B. muli (multiply immediate) stores into register C the result of multiplying register A and value B. Bitwise AND: banr (bitwise AND register) stores into register C the result of the bitwise AND of register A and register B. bani (bitwise AND immediate) stores into register C the result of the bitwise AND of register A and value B. Bitwise OR: borr (bitwise OR register) stores into register C the result of the bitwise OR of register A and register B. bori (bitwise OR immediate) stores into register C the result of the bitwise OR of register A and value B. Assignment: setr (set register) copies the contents of register A into register C. (Input B is ignored.) seti (set immediate) stores value A into register C. (Input B is ignored.) Greater-than testing: gtir (greater-than immediate/register) sets register C to 1 if value A is greater than register B. Otherwise, register C is set to 0. gtri (greater-than register/immediate) sets register C to 1 if register A is greater than value B. Otherwise, register C is set to 0. gtrr (greater-than register/register) sets register C to 1 if register A is greater than register B. Otherwise, register C is set to 0. Equality testing: eqir (equal immediate/register) sets register C to 1 if value A is equal to register B. Otherwise, register C is set to 0. eqri (equal register/immediate) sets register C to 1 if register A is equal to value B. Otherwise, register C is set to 0. eqrr (equal register/register) sets register C to 1 if register A is equal to register B. Otherwise, register C is set to 0. Unfortunately, while the manual gives the name of each opcode, it doesn't seem to indicate the number. However, you can monitor the CPU to see the contents of the registers before and after instructions are executed to try to work them out. Each opcode has a number from 0 through 15, but the manual doesn't say which is which. For example, suppose you capture the following sample: Before: [3, 2, 1, 1] 9 2 1 2 After: [3, 2, 2, 1] This sample shows the effect of the instruction 9 2 1 2 on the registers. Before the instruction is executed, register 0 has value 3, register 1 has value 2, and registers 2 and 3 have value 1. After the instruction is executed, register 2's value becomes 2. The instruction itself, 9 2 1 2, means that opcode 9 was executed with A=2, B=1, and C=2. Opcode 9 could be any of the 16 opcodes listed above, but only three of them behave in a way that would cause the result shown in the sample: Opcode 9 could be mulr: register 2 (which has a value of 1) times register 1 (which has a value of 2) produces 2, which matches the value stored in the output register, register 2. Opcode 9 could be addi: register 2 (which has a value of 1) plus value 1 produces 2, which matches the value stored in the output register, register 2. Opcode 9 could be seti: value 2 matches the value stored in the output register, register 2; the number given for B is irrelevant. None of the other opcodes produce the result captured in the sample. Because of this, the sample above behaves like three opcodes. You collect many of these samples (the first section of your puzzle input). The manual also includes a small test program (the second section of your puzzle input) - you can ignore it for now. Ignoring the opcode numbers, how many samples in your puzzle input behave like three or more opcodes?
240
--- Day 16: Permutation Promenade --- You come upon a very unusual sight; a group of programs here appear to be dancing. There are sixteen programs in total, named a through p. They start by standing in a line: a stands in position 0, b stands in position 1, and so on until p, which stands in position 15. The programs' dance consists of a sequence of dance moves: Spin, written sX, makes X programs move from the end to the front, but maintain their order otherwise. (For example, s3 on abcde produces cdeab). Exchange, written xA/B, makes the programs at positions A and B swap places. Partner, written pA/B, makes the programs named A and B swap places. For example, with only five programs standing in a line (abcde), they could do the following dance: s1, a spin of size 1: eabcd. x3/4, swapping the last two programs: eabdc. pe/b, swapping programs e and b: baedc. After finishing their dance, the programs end up in order baedc. You watch the dance for a while and record their dance moves (your puzzle input). In what order are the programs standing after their dance?
241
--- Day 23: Amphipod --- A group of amphipods notice your fancy submarine and flag you down. "With such an impressive shell," one amphipod says, "surely you can help us with a question that has stumped our best scientists." They go on to explain that a group of timid, stubborn amphipods live in a nearby burrow. Four types of amphipods live there: Amber (A), Bronze (B), Copper (C), and Desert (D). They live in a burrow that consists of a hallway and four side rooms. The side rooms are initially full of amphipods, and the hallway is initially empty. They give you a diagram of the situation (your puzzle input), including locations of each amphipod (A, B, C, or D, each of which is occupying an otherwise open space), walls (#), and open space (.). For example: ############# #...........# ###B#C#B#D### #A#D#C#A# ######### The amphipods would like a method to organize every amphipod into side rooms so that each side room contains one type of amphipod and the types are sorted A-D going left to right, like this: ############# #...........# ###A#B#C#D### #A#B#C#D# ######### Amphipods can move up, down, left, or right so long as they are moving into an unoccupied open space. Each type of amphipod requires a different amount of energy to move one step: Amber amphipods require 1 energy per step, Bronze amphipods require 10 energy, Copper amphipods require 100, and Desert ones require 1000. The amphipods would like you to find a way to organize the amphipods that requires the least total energy. However, because they are timid and stubborn, the amphipods have some extra rules: Amphipods will never stop on the space immediately outside any room. They can move into that space so long as they immediately continue moving. (Specifically, this refers to the four open spaces in the hallway that are directly above an amphipod starting position.) Amphipods will never move from the hallway into a room unless that room is their destination room and that room contains no amphipods which do not also have that room as their own destination. If an amphipod's starting room is not its destination room, it can stay in that room until it leaves the room. (For example, an Amber amphipod will not move from the hallway into the right three rooms, and will only move into the leftmost room if that room is empty or if it only contains other Amber amphipods.) Once an amphipod stops moving in the hallway, it will stay in that spot until it can move into a room. (That is, once any amphipod starts moving, any other amphipods currently in the hallway are locked in place and will not move again until they can move fully into a room.) In the above example, the amphipods can be organized using a minimum of 12521 energy. One way to do this is shown below. Starting configuration: ############# #...........# ###B#C#B#D### #A#D#C#A# ######### One Bronze amphipod moves into the hallway, taking 4 steps and using 40 energy: ############# #...B.......# ###B#C#.#D### #A#D#C#A# ######### The only Copper amphipod not in its side room moves there, taking 4 steps and using 400 energy: ############# #...B.......# ###B#.#C#D### #A#D#C#A# ######### A Desert amphipod moves out of the way, taking 3 steps and using 3000 energy, and then the Bronze amphipod takes its place, taking 3 steps and using 30 energy: ############# #.....D.....# ###B#.#C#D### #A#B#C#A# ######### The leftmost Bronze amphipod moves to its room using 40 energy: ############# #.....D.....# ###.#B#C#D### #A#B#C#A# ######### Both amphipods in the rightmost room move into the hallway, using 2003 energy in total: ############# #.....D.D.A.# ###.#B#C#.### #A#B#C#.# ######### Both Desert amphipods move into the rightmost room using 7000 energy: ############# #.........A.# ###.#B#C#D### #A#B#C#D# ######### Finally, the last Amber amphipod moves into its room, using 8 energy: ############# #...........# ###A#B#C#D### #A#B#C#D# ######### What is the least energy required to organize the amphipods? Your puzzle answer was 15538. --- Part Two --- As you prepare to give the amphipods your solution, you notice that the diagram they handed you was actually folded up. As you unfold it, you discover an extra part of the diagram. Between the first and second lines of text that contain amphipod starting positions, insert the following lines: #D#C#B#A# #D#B#A#C# So, the above example now becomes: ############# #...........# ###B#C#B#D### #D#C#B#A# #D#B#A#C# #A#D#C#A# ######### The amphipods still want to be organized into rooms similar to before: ############# #...........# ###A#B#C#D### #A#B#C#D# #A#B#C#D# #A#B#C#D# ######### In this updated example, the least energy required to organize these amphipods is 44169: ############# #...........# ###B#C#B#D### #D#C#B#A# #D#B#A#C# #A#D#C#A# ######### ############# #..........D# ###B#C#B#.### #D#C#B#A# #D#B#A#C# #A#D#C#A# ######### ############# #A.........D# ###B#C#B#.### #D#C#B#.# #D#B#A#C# #A#D#C#A# ######### ############# #A........BD# ###B#C#.#.### #D#C#B#.# #D#B#A#C# #A#D#C#A# ######### ############# #A......B.BD# ###B#C#.#.### #D#C#.#.# #D#B#A#C# #A#D#C#A# ######### ############# #AA.....B.BD# ###B#C#.#.### #D#C#.#.# #D#B#.#C# #A#D#C#A# ######### ############# #AA.....B.BD# ###B#.#.#.### #D#C#.#.# #D#B#C#C# #A#D#C#A# ######### ############# #AA.....B.BD# ###B#.#.#.### #D#.#C#.# #D#B#C#C# #A#D#C#A# ######### ############# #AA...B.B.BD# ###B#.#.#.### #D#.#C#.# #D#.#C#C# #A#D#C#A# ######### ############# #AA.D.B.B.BD# ###B#.#.#.### #D#.#C#.# #D#.#C#C# #A#.#C#A# ######### ############# #AA.D...B.BD# ###B#.#.#.### #D#.#C#.# #D#.#C#C# #A#B#C#A# ######### ############# #AA.D.....BD# ###B#.#.#.### #D#.#C#.# #D#B#C#C# #A#B#C#A# ######### ############# #AA.D......D# ###B#.#.#.### #D#B#C#.# #D#B#C#C# #A#B#C#A# ######### ############# #AA.D......D# ###B#.#C#.### #D#B#C#.# #D#B#C#.# #A#B#C#A# ######### ############# #AA.D.....AD# ###B#.#C#.### #D#B#C#.# #D#B#C#.# #A#B#C#.# ######### ############# #AA.......AD# ###B#.#C#.### #D#B#C#.# #D#B#C#.# #A#B#C#D# ######### ############# #AA.......AD# ###.#B#C#.### #D#B#C#.# #D#B#C#.# #A#B#C#D# ######### ############# #AA.......AD# ###.#B#C#.### #.#B#C#.# #D#B#C#D# #A#B#C#D# ######### ############# #AA.D.....AD# ###.#B#C#.### #.#B#C#.# #.#B#C#D# #A#B#C#D# ######### ############# #A..D.....AD# ###.#B#C#.### #.#B#C#.# #A#B#C#D# #A#B#C#D# ######### ############# #...D.....AD# ###.#B#C#.### #A#B#C#.# #A#B#C#D# #A#B#C#D# ######### ############# #.........AD# ###.#B#C#.### #A#B#C#D# #A#B#C#D# #A#B#C#D# ######### ############# #..........D# ###A#B#C#.### #A#B#C#D# #A#B#C#D# #A#B#C#D# ######### ############# #...........# ###A#B#C#D### #A#B#C#D# #A#B#C#D# #A#B#C#D# ######### Using the initial configuration from the full diagram, what is the least energy required to organize the amphipods?
242
--- Day 21: Chronal Conversion --- You should have been watching where you were going, because as you wander the new North Pole base, you trip and fall into a very deep hole! Just kidding. You're falling through time again. If you keep up your current pace, you should have resolved all of the temporal anomalies by the next time the device activates. Since you have very little interest in browsing history in 500-year increments for the rest of your life, you need to find a way to get back to your present time. After a little research, you discover two important facts about the behavior of the device: First, you discover that the device is hard-wired to always send you back in time in 500-year increments. Changing this is probably not feasible. Second, you discover the activation system (your puzzle input) for the time travel module. Currently, it appears to run forever without halting. If you can cause the activation system to halt at a specific moment, maybe you can make the device send you so far back in time that you cause an integer underflow in time itself and wrap around back to your current time! The device executes the program as specified in manual section one and manual section two. Your goal is to figure out how the program works and cause it to halt. You can only control register 0; every other register begins at 0 as usual. Because time travel is a dangerous activity, the activation system begins with a few instructions which verify that bitwise AND (via bani) does a numeric operation and not an operation as if the inputs were interpreted as strings. If the test fails, it enters an infinite loop re-running the test instead of allowing the program to execute normally. If the test passes, the program continues, and assumes that all other bitwise operations (banr, bori, and borr) also interpret their inputs as numbers. (Clearly, the Elves who wrote this system were worried that someone might introduce a bug while trying to emulate this system with a scripting language.) What is the lowest non-negative integer value for register 0 that causes the program to halt after executing the fewest instructions? (Executing the same instruction multiple times counts as multiple instructions executed.)
243
--- Day 16: Dragon Checksum --- You're done scanning this part of the network, but you've left traces of your presence. You need to overwrite some disks with random-looking data to cover your tracks and update the local security system with a new checksum for those disks. For the data to not be suspicious, it needs to have certain properties; purely random data will be detected as tampering. To generate appropriate random data, you'll need to use a modified dragon curve. Start with an appropriate initial state (your puzzle input). Then, so long as you don't have enough data yet to fill the disk, repeat the following steps: Call the data you have at this point "a". Make a copy of "a"; call this copy "b". Reverse the order of the characters in "b". In "b", replace all instances of 0 with 1 and all 1s with 0. The resulting data is "a", then a single 0, then "b". For example, after a single step of this process, 1 becomes 100. 0 becomes 001. 11111 becomes 11111000000. 111100001010 becomes 1111000010100101011110000. Repeat these steps until you have enough data to fill the desired disk. Once the data has been generated, you also need to create a checksum of that data. Calculate the checksum only for the data that fits on the disk, even if you generated more data than that in the previous step. The checksum for some given data is created by considering each non-overlapping pair of characters in the input data. If the two characters match (00 or 11), the next checksum character is a 1. If the characters do not match (01 or 10), the next checksum character is a 0. This should produce a new string which is exactly half as long as the original. If the length of the checksum is even, repeat the process until you end up with a checksum with an odd length. For example, suppose we want to fill a disk of length 12, and when we finally generate a string of at least length 12, the first 12 characters are 110010110100. To generate its checksum: Consider each pair: 11, 00, 10, 11, 01, 00. These are same, same, different, same, different, same, producing 110101. The resulting string has length 6, which is even, so we repeat the process. The pairs are 11 (same), 01 (different), 01 (different). This produces the checksum 100, which has an odd length, so we stop. Therefore, the checksum for 110010110100 is 100. Combining all of these steps together, suppose you want to fill a disk of length 20 using an initial state of 10000: Because 10000 is too short, we first use the modified dragon curve to make it longer. After one round, it becomes 10000011110 (11 characters), still too short. After two rounds, it becomes 10000011110010000111110 (23 characters), which is enough. Since we only need 20, but we have 23, we get rid of all but the first 20 characters: 10000011110010000111. Next, we start calculating the checksum; after one round, we have 0111110101, which 10 characters long (even), so we continue. After two rounds, we have 01100, which is 5 characters long (odd), so we are done. In this example, the correct checksum would therefore be 01100. The first disk you have to fill has length 272. Using the initial state in your puzzle input, what is the correct checksum?
244
--- Day 16: Packet Decoder --- As you leave the cave and reach open waters, you receive a transmission from the Elves back on the ship. The transmission was sent using the Buoyancy Interchange Transmission System (BITS), a method of packing numeric expressions into a binary sequence. Your submarine's computer has saved the transmission in hexadecimal (your puzzle input). The first step of decoding the message is to convert the hexadecimal representation into binary. Each character of hexadecimal corresponds to four bits of binary data: 0 = 0000 1 = 0001 2 = 0010 3 = 0011 4 = 0100 5 = 0101 6 = 0110 7 = 0111 8 = 1000 9 = 1001 A = 1010 B = 1011 C = 1100 D = 1101 E = 1110 F = 1111 The BITS transmission contains a single packet at its outermost layer which itself contains many other packets. The hexadecimal representation of this packet might encode a few extra 0 bits at the end; these are not part of the transmission and should be ignored. Every packet begins with a standard header: the first three bits encode the packet version, and the next three bits encode the packet type ID. These two values are numbers; all numbers encoded in any packet are represented as binary with the most significant bit first. For example, a version encoded as the binary sequence 100 represents the number 4. Packets with type ID 4 represent a literal value. Literal value packets encode a single binary number. To do this, the binary number is padded with leading zeroes until its length is a multiple of four bits, and then it is broken into groups of four bits. Each group is prefixed by a 1 bit except the last group, which is prefixed by a 0 bit. These groups of five bits immediately follow the packet header. For example, the hexadecimal string D2FE28 becomes: 110100101111111000101000 VVVTTTAAAAABBBBBCCCCC Below each bit is a label indicating its purpose: The three bits labeled V (110) are the packet version, 6. The three bits labeled T (100) are the packet type ID, 4, which means the packet is a literal value. The five bits labeled A (10111) start with a 1 (not the last group, keep reading) and contain the first four bits of the number, 0111. The five bits labeled B (11110) start with a 1 (not the last group, keep reading) and contain four more bits of the number, 1110. The five bits labeled C (00101) start with a 0 (last group, end of packet) and contain the last four bits of the number, 0101. The three unlabeled 0 bits at the end are extra due to the hexadecimal representation and should be ignored. So, this packet represents a literal value with binary representation 011111100101, which is 2021 in decimal. Every other type of packet (any packet with a type ID other than 4) represent an operator that performs some calculation on one or more sub-packets contained within. Right now, the specific operations aren't important; focus on parsing the hierarchy of sub-packets. An operator packet contains one or more packets. To indicate which subsequent binary data represents its sub-packets, an operator packet can use one of two modes indicated by the bit immediately after the packet header; this is called the length type ID: If the length type ID is 0, then the next 15 bits are a number that represents the total length in bits of the sub-packets contained by this packet. If the length type ID is 1, then the next 11 bits are a number that represents the number of sub-packets immediately contained by this packet. Finally, after the length type ID bit and the 15-bit or 11-bit field, the sub-packets appear. For example, here is an operator packet (hexadecimal string 38006F45291200) with length type ID 0 that contains two sub-packets: 00111000000000000110111101000101001010010001001000000000 VVVTTTILLLLLLLLLLLLLLLAAAAAAAAAAABBBBBBBBBBBBBBBB The three bits labeled V (001) are the packet version, 1. The three bits labeled T (110) are the packet type ID, 6, which means the packet is an operator. The bit labeled I (0) is the length type ID, which indicates that the length is a 15-bit number representing the number of bits in the sub-packets. The 15 bits labeled L (000000000011011) contain the length of the sub-packets in bits, 27. The 11 bits labeled A contain the first sub-packet, a literal value representing the number 10. The 16 bits labeled B contain the second sub-packet, a literal value representing the number 20. After reading 11 and 16 bits of sub-packet data, the total length indicated in L (27) is reached, and so parsing of this packet stops. As another example, here is an operator packet (hexadecimal string EE00D40C823060) with length type ID 1 that contains three sub-packets: 11101110000000001101010000001100100000100011000001100000 VVVTTTILLLLLLLLLLLAAAAAAAAAAABBBBBBBBBBBCCCCCCCCCCC The three bits labeled V (111) are the packet version, 7. The three bits labeled T (011) are the packet type ID, 3, which means the packet is an operator. The bit labeled I (1) is the length type ID, which indicates that the length is a 11-bit number representing the number of sub-packets. The 11 bits labeled L (00000000011) contain the number of sub-packets, 3. The 11 bits labeled A contain the first sub-packet, a literal value representing the number 1. The 11 bits labeled B contain the second sub-packet, a literal value representing the number 2. The 11 bits labeled C contain the third sub-packet, a literal value representing the number 3. After reading 3 complete sub-packets, the number of sub-packets indicated in L (3) is reached, and so parsing of this packet stops. For now, parse the hierarchy of the packets throughout the transmission and add up all of the version numbers. Here are a few more examples of hexadecimal-encoded transmissions: 8A004A801A8002F478 represents an operator packet (version 4) which contains an operator packet (version 1) which contains an operator packet (version 5) which contains a literal value (version 6); this packet has a version sum of 16. 620080001611562C8802118E34 represents an operator packet (version 3) which contains two sub-packets; each sub-packet is an operator packet that contains two literal values. This packet has a version sum of 12. C0015000016115A2E0802F182340 has the same structure as the previous example, but the outermost packet uses a different length type ID. This packet has a version sum of 23. A0016C880162017C3686B18A3D4780 is an operator packet that contains an operator packet that contains an operator packet that contains five literal values; it has a version sum of 31. Decode the structure of your hexadecimal-encoded BITS transmission; what do you get if you add up the version numbers in all packets? Your puzzle answer was 943. --- Part Two --- Now that you have the structure of your transmission decoded, you can calculate the value of the expression it represents. Literal values (type ID 4) represent a single number as described above. The remaining type IDs are more interesting: Packets with type ID 0 are sum packets - their value is the sum of the values of their sub-packets. If they only have a single sub-packet, their value is the value of the sub-packet. Packets with type ID 1 are product packets - their value is the result of multiplying together the values of their sub-packets. If they only have a single sub-packet, their value is the value of the sub-packet. Packets with type ID 2 are minimum packets - their value is the minimum of the values of their sub-packets. Packets with type ID 3 are maximum packets - their value is the maximum of the values of their sub-packets. Packets with type ID 5 are greater than packets - their value is 1 if the value of the first sub-packet is greater than the value of the second sub-packet; otherwise, their value is 0. These packets always have exactly two sub-packets. Packets with type ID 6 are less than packets - their value is 1 if the value of the first sub-packet is less than the value of the second sub-packet; otherwise, their value is 0. These packets always have exactly two sub-packets. Packets with type ID 7 are equal to packets - their value is 1 if the value of the first sub-packet is equal to the value of the second sub-packet; otherwise, their value is 0. These packets always have exactly two sub-packets. Using these rules, you can now work out the value of the outermost packet in your BITS transmission. For example: C200B40A82 finds the sum of 1 and 2, resulting in the value 3. 04005AC33890 finds the product of 6 and 9, resulting in the value 54. 880086C3E88112 finds the minimum of 7, 8, and 9, resulting in the value 7. CE00C43D881120 finds the maximum of 7, 8, and 9, resulting in the value 9. D8005AC2A8F0 produces 1, because 5 is less than 15. F600BC2D8F produces 0, because 5 is not greater than 15. 9C005AC2F8F0 produces 0, because 5 is not equal to 15. 9C0141080250320F1802104A08 produces 1, because 1 + 3 = 2 * 2. What do you get if you evaluate the expression represented by your hexadecimal-encoded BITS transmission?
245
--- Day 21: Scrambled Letters and Hash --- The computer system you're breaking into uses a weird scrambling function to store its passwords. It shouldn't be much trouble to create your own scrambled password so you can add it to the system; you just have to implement the scrambler. The scrambling function is a series of operations (the exact list is provided in your puzzle input). Starting with the password to be scrambled, apply each operation in succession to the string. The individual operations behave as follows: swap position X with position Y means that the letters at indexes X and Y (counting from 0) should be swapped. swap letter X with letter Y means that the letters X and Y should be swapped (regardless of where they appear in the string). rotate left/right X steps means that the whole string should be rotated; for example, one right rotation would turn abcd into dabc. rotate based on position of letter X means that the whole string should be rotated to the right based on the index of letter X (counting from 0) as determined before this instruction does any rotations. Once the index is determined, rotate the string to the right one time, plus a number of times equal to that index, plus one additional time if the index was at least 4. reverse positions X through Y means that the span of letters at indexes X through Y (including the letters at X and Y) should be reversed in order. move position X to position Y means that the letter which is at index X should be removed from the string, then inserted such that it ends up at index Y. For example, suppose you start with abcde and perform the following operations: swap position 4 with position 0 swaps the first and last letters, producing the input for the next step, ebcda. swap letter d with letter b swaps the positions of d and b: edcba. reverse positions 0 through 4 causes the entire string to be reversed, producing abcde. rotate left 1 step shifts all letters left one position, causing the first letter to wrap to the end of the string: bcdea. move position 1 to position 4 removes the letter at position 1 (c), then inserts it at position 4 (the end of the string): bdeac. move position 3 to position 0 removes the letter at position 3 (a), then inserts it at position 0 (the front of the string): abdec. rotate based on position of letter b finds the index of letter b (1), then rotates the string right once plus a number of times equal to that index (2): ecabd. rotate based on position of letter d finds the index of letter d (4), then rotates the string right once, plus a number of times equal to that index, plus an additional time because the index was at least 4, for a total of 6 right rotations: decab. After these steps, the resulting scrambled password is decab. Now, you just need to generate a new scrambled password and you can access the system. Given the list of scrambling operations in your puzzle input, what is the result of scrambling abcdefgh?
246
--- Day 16: Permutation Promenade --- You come upon a very unusual sight; a group of programs here appear to be dancing. There are sixteen programs in total, named a through p. They start by standing in a line: a stands in position 0, b stands in position 1, and so on until p, which stands in position 15. The programs' dance consists of a sequence of dance moves: Spin, written sX, makes X programs move from the end to the front, but maintain their order otherwise. (For example, s3 on abcde produces cdeab). Exchange, written xA/B, makes the programs at positions A and B swap places. Partner, written pA/B, makes the programs named A and B swap places. For example, with only five programs standing in a line (abcde), they could do the following dance: s1, a spin of size 1: eabcd. x3/4, swapping the last two programs: eabdc. pe/b, swapping programs e and b: baedc. After finishing their dance, the programs end up in order baedc. You watch the dance for a while and record their dance moves (your puzzle input). In what order are the programs standing after their dance? Your puzzle answer was cknmidebghlajpfo. --- Part Two --- Now that you're starting to get a feel for the dance moves, you turn your attention to the dance as a whole. Keeping the positions they ended up in from their previous dance, the programs perform it again and again: including the first dance, a total of one billion (1000000000) times. In the example above, their second dance would begin with the order baedc, and use the same dance moves: s1, a spin of size 1: cbaed. x3/4, swapping the last two programs: cbade. pe/b, swapping programs e and b: ceadb. In what order are the programs standing after their billion dances?
247
--- Day 17: Clumsy Crucible --- The lava starts flowing rapidly once the Lava Production Facility is operational. As you leave, the reindeer offers you a parachute, allowing you to quickly reach Gear Island. As you descend, your bird's-eye view of Gear Island reveals why you had trouble finding anyone on your way up: half of Gear Island is empty, but the half below you is a giant factory city! You land near the gradually-filling pool of lava at the base of your new lavafall. Lavaducts will eventually carry the lava throughout the city, but to make use of it immediately, Elves are loading it into large crucibles on wheels. The crucibles are top-heavy and pushed by hand. Unfortunately, the crucibles become very difficult to steer at high speeds, and so it can be hard to go in a straight line for very long. To get Desert Island the machine parts it needs as soon as possible, you'll need to find the best way to get the crucible from the lava pool to the machine parts factory. To do this, you need to minimize heat loss while choosing a route that doesn't require the crucible to go in a straight line for too long. Fortunately, the Elves here have a map (your puzzle input) that uses traffic patterns, ambient temperature, and hundreds of other parameters to calculate exactly how much heat loss can be expected for a crucible entering any particular city block. For example: 2413432311323 3215453535623 3255245654254 3446585845452 4546657867536 1438598798454 4457876987766 3637877979653 4654967986887 4564679986453 1224686865563 2546548887735 4322674655533 Each city block is marked by a single digit that represents the amount of heat loss if the crucible enters that block. The starting point, the lava pool, is the top-left city block; the destination, the machine parts factory, is the bottom-right city block. (Because you already start in the top-left block, you don't incur that block's heat loss unless you leave that block and then return to it.) Because it is difficult to keep the top-heavy crucible going in a straight line for very long, it can move at most three blocks in a single direction before it must turn 90 degrees left or right. The crucible also can't reverse direction; after entering each city block, it may only turn left, continue straight, or turn right. One way to minimize heat loss is this path: 2>>34^>>>1323 32v>>>35v5623 32552456v>>54 3446585845v52 4546657867v>6 14385987984v4 44578769877v6 36378779796v> 465496798688v 456467998645v 12246868655<v 25465488877v5 43226746555v> This path never moves more than three consecutive blocks in the same direction and incurs a heat loss of only 102. Directing the crucible from the lava pool to the machine parts factory, but not moving more than three consecutive blocks in the same direction, what is the least heat loss it can incur?
248
--- Day 13: Distress Signal --- 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: If both values are integers, the lower integer should come first. If the left integer is lower than the right integer, the inputs are in the right order. If the left integer is higher than the right integer, the inputs are not in the right order. Otherwise, the inputs are the same integer; continue checking the next part of the input. If both values are lists, compare the first value of each list, then the second value, and so on. If the left list runs out of items first, the inputs are in the right order. If the right list runs out of items first, the inputs are not in the right order. If the lists are the same length and no comparison makes a decision about the order, continue checking the next part of the input. If exactly one value is an integer, convert the integer to a list which contains that integer as its only value, then retry the comparison. For example, if comparing [0,0,0] and 2, convert the right value to [2] (a list containing 2); the result is then found by instead comparing [0,0,0] and [2]. 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? Your puzzle answer was 5588. --- Part Two --- 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?
249
--- Day 1: Trebuchet?! --- Something is wrong with global snow production, and you've been selected to take a look. The Elves have even given you a map; on it, they've used stars to mark the top fifty locations that are likely to be having problems. You've been doing this long enough to know that to restore snow operations, you need to check all fifty stars by December 25th. Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! You try to ask why they can't just use a weather machine ("not powerful enough") and where they're even sending you ("the sky") and why your map looks mostly blank ("you sure ask a lot of questions") and hang on did you just say the sky ("of course, where do you think snow comes from") when you realize that the Elves are already loading you into a trebuchet ("please hold still, we need to strap you in"). As they're making the final adjustments, they discover that their calibration document (your puzzle input) has been amended by a very young Elf who was apparently just excited to show off her art skills. Consequently, the Elves are having trouble reading the values on the document. The newly-improved calibration document consists of lines of text; each line originally contained a specific calibration value that the Elves now need to recover. On each line, the calibration value can be found by combining the first digit and the last digit (in that order) to form a single two-digit number. For example: 1abc2 pqr3stu8vwx a1b2c3d4e5f treb7uchet In this example, the calibration values of these four lines are 12, 38, 15, and 77. Adding these together produces 142. Consider your entire calibration document. What is the sum of all of the calibration values?
250
--- Day 5: Print Queue --- Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. The North Pole printing department is busier than ever this close to Christmas, and while The Historians continue their search of this historically significant facility, an Elf operating a very familiar printer beckons you over. The Elf must recognize you, because they waste no time explaining that the new sleigh launch safety manual updates won't print correctly. Failure to update the safety manuals would be dire indeed, so you offer your services. Safety protocols clearly indicate that new pages for the safety manuals must be printed in a very specific order. The notation X|Y means that if both page number X and page number Y are to be produced as part of an update, page number X must be printed at some point before page number Y. The Elf has for you both the page ordering rules and the pages to produce in each update (your puzzle input), but can't figure out whether each update has the pages in the right order. For example: 47|53 97|13 97|61 97|47 75|29 61|13 75|53 29|13 97|29 53|29 61|53 97|53 61|29 47|13 75|47 97|75 47|61 75|61 47|29 75|13 53|13 75,47,61,53,29 97,61,53,29,13 75,29,13 75,97,47,61,53 61,13,29 97,13,75,29,47 The first section specifies the page ordering rules, one per line. The first rule, 47|53, means that if an update includes both page number 47 and page number 53, then page number 47 must be printed at some point before page number 53. (47 doesn't necessarily need to be immediately before 53; other pages are allowed to be between them.) The second section specifies the page numbers of each update. Because most safety manuals are different, the pages needed in the updates are different too. The first update, 75,47,61,53,29, means that the update consists of page numbers 75, 47, 61, 53, and 29. To get the printers going as soon as possible, start by identifying which updates are already in the right order. In the above example, the first update (75,47,61,53,29) is in the right order: 75 is correctly first because there are rules that put each other page after it: 75|47, 75|61, 75|53, and 75|29. 47 is correctly second because 75 must be before it (75|47) and every other page must be after it according to 47|61, 47|53, and 47|29. 61 is correctly in the middle because 75 and 47 are before it (75|61 and 47|61) and 53 and 29 are after it (61|53 and 61|29). 53 is correctly fourth because it is before page number 29 (53|29). 29 is the only page left and so is correctly last. Because the first update does not include some page numbers, the ordering rules involving those missing page numbers are ignored. The second and third updates are also in the correct order according to the rules. Like the first update, they also do not include every page number, and so only some of the ordering rules apply - within each update, the ordering rules that involve missing page numbers are not used. The fourth update, 75,97,47,61,53, is not in the correct order: it would print 75 before 97, which violates the rule 97|75. The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. For some reason, the Elves also need to know the middle page number of each update being printed. Because you are currently only printing the correctly-ordered updates, you will need to find the middle page number of each correctly-ordered update. In the above example, the correctly-ordered updates are: 75,47,61,53,29 97,61,53,29,13 75,29,13 These have middle page numbers of 61, 53, and 29 respectively. Adding these page numbers together gives 143. Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. Determine which updates are already in the correct order. What do you get if you add up the middle page number from those correctly-ordered updates? Your puzzle answer was 4957. The first half of this puzzle is complete! It provides one gold star: * --- Part Two --- While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. For each of the incorrectly-ordered updates, use the page ordering rules to put the page numbers in the right order. For the above example, here are the three incorrectly-ordered updates and their correct orderings: 75,97,47,61,53 becomes 97,75,47,61,53. 61,13,29 becomes 61,29,13. 97,13,75,29,47 becomes 97,75,47,29,13. After taking only the incorrectly-ordered updates and ordering them correctly, their middle page numbers are 47, 29, and 47. Adding these together produces 123. Find the updates which are not in the correct order. What do you get if you add up the middle page numbers after correctly ordering just those updates?
251
--- Day 23: Amphipod --- A group of amphipods notice your fancy submarine and flag you down. "With such an impressive shell," one amphipod says, "surely you can help us with a question that has stumped our best scientists." They go on to explain that a group of timid, stubborn amphipods live in a nearby burrow. Four types of amphipods live there: Amber (A), Bronze (B), Copper (C), and Desert (D). They live in a burrow that consists of a hallway and four side rooms. The side rooms are initially full of amphipods, and the hallway is initially empty. They give you a diagram of the situation (your puzzle input), including locations of each amphipod (A, B, C, or D, each of which is occupying an otherwise open space), walls (#), and open space (.). For example: ############# #...........# ###B#C#B#D### #A#D#C#A# ######### The amphipods would like a method to organize every amphipod into side rooms so that each side room contains one type of amphipod and the types are sorted A-D going left to right, like this: ############# #...........# ###A#B#C#D### #A#B#C#D# ######### Amphipods can move up, down, left, or right so long as they are moving into an unoccupied open space. Each type of amphipod requires a different amount of energy to move one step: Amber amphipods require 1 energy per step, Bronze amphipods require 10 energy, Copper amphipods require 100, and Desert ones require 1000. The amphipods would like you to find a way to organize the amphipods that requires the least total energy. However, because they are timid and stubborn, the amphipods have some extra rules: Amphipods will never stop on the space immediately outside any room. They can move into that space so long as they immediately continue moving. (Specifically, this refers to the four open spaces in the hallway that are directly above an amphipod starting position.) Amphipods will never move from the hallway into a room unless that room is their destination room and that room contains no amphipods which do not also have that room as their own destination. If an amphipod's starting room is not its destination room, it can stay in that room until it leaves the room. (For example, an Amber amphipod will not move from the hallway into the right three rooms, and will only move into the leftmost room if that room is empty or if it only contains other Amber amphipods.) Once an amphipod stops moving in the hallway, it will stay in that spot until it can move into a room. (That is, once any amphipod starts moving, any other amphipods currently in the hallway are locked in place and will not move again until they can move fully into a room.) In the above example, the amphipods can be organized using a minimum of 12521 energy. One way to do this is shown below. Starting configuration: ############# #...........# ###B#C#B#D### #A#D#C#A# ######### One Bronze amphipod moves into the hallway, taking 4 steps and using 40 energy: ############# #...B.......# ###B#C#.#D### #A#D#C#A# ######### The only Copper amphipod not in its side room moves there, taking 4 steps and using 400 energy: ############# #...B.......# ###B#.#C#D### #A#D#C#A# ######### A Desert amphipod moves out of the way, taking 3 steps and using 3000 energy, and then the Bronze amphipod takes its place, taking 3 steps and using 30 energy: ############# #.....D.....# ###B#.#C#D### #A#B#C#A# ######### The leftmost Bronze amphipod moves to its room using 40 energy: ############# #.....D.....# ###.#B#C#D### #A#B#C#A# ######### Both amphipods in the rightmost room move into the hallway, using 2003 energy in total: ############# #.....D.D.A.# ###.#B#C#.### #A#B#C#.# ######### Both Desert amphipods move into the rightmost room using 7000 energy: ############# #.........A.# ###.#B#C#D### #A#B#C#D# ######### Finally, the last Amber amphipod moves into its room, using 8 energy: ############# #...........# ###A#B#C#D### #A#B#C#D# ######### What is the least energy required to organize the amphipods?
252
--- Day 13: Shuttle Search --- Your ferry can make it safely to a nearby port, but it won't get much further. When you call to book another ship, you discover that no ships embark from that port to your vacation island. You'll need to get from the port to the nearest airport. Fortunately, a shuttle bus service is available to bring you from the sea port to the airport! Each bus has an ID number that also indicates how often the bus leaves for the airport. Bus schedules are defined based on a timestamp that measures the number of minutes since some fixed reference point in the past. At timestamp 0, every bus simultaneously departed from the sea port. After that, each bus travels to the airport, then various other locations, and finally returns to the sea port to repeat its journey forever. The time this loop takes a particular bus is also its ID number: the bus with ID 5 departs from the sea port at timestamps 0, 5, 10, 15, and so on. The bus with ID 11 departs at 0, 11, 22, 33, and so on. If you are there when the bus departs, you can ride that bus to the airport! Your notes (your puzzle input) consist of two lines. The first line is your estimate of the earliest timestamp you could depart on a bus. The second line lists the bus IDs that are in service according to the shuttle company; entries that show x must be out of service, so you decide to ignore them. To save time once you arrive, your goal is to figure out the earliest bus you can take to the airport. (There will be exactly one such bus.) For example, suppose you have the following notes: 939 7,13,x,x,59,x,31,19 Here, the earliest timestamp you could depart is 939, and the bus IDs in service are 7, 13, 59, 31, and 19. Near timestamp 939, these bus IDs depart at the times marked D: time bus 7 bus 13 bus 59 bus 31 bus 19 929 . . . . . 930 . . . D . 931 D . . . D 932 . . . . . 933 . . . . . 934 . . . . . 935 . . . . . 936 . D . . . 937 . . . . . 938 D . . . . 939 . . . . . 940 . . . . . 941 . . . . . 942 . . . . . 943 . . . . . 944 . . D . . 945 D . . . . 946 . . . . . 947 . . . . . 948 . . . . . 949 . D . . . The earliest bus you could take is bus ID 59. It doesn't depart until timestamp 944, so you would need to wait 944 - 939 = 5 minutes before it departs. Multiplying the bus ID by the number of minutes you'd need to wait gives 295. What is the ID of the earliest bus you can take to the airport multiplied by the number of minutes you'll need to wait for that bus? Your puzzle answer was 261. --- Part Two --- The shuttle company is running a contest: one gold coin for anyone that can find the earliest timestamp such that the first bus ID departs at that time and each subsequent listed bus ID departs at that subsequent minute. (The first line in your input is no longer relevant.) For example, suppose you have the same list of bus IDs as above: 7,13,x,x,59,x,31,19 An x in the schedule means there are no constraints on what bus IDs must depart at that time. This means you are looking for the earliest timestamp (called t) such that: Bus ID 7 departs at timestamp t. Bus ID 13 departs one minute after timestamp t. There are no requirements or restrictions on departures at two or three minutes after timestamp t. Bus ID 59 departs four minutes after timestamp t. There are no requirements or restrictions on departures at five minutes after timestamp t. Bus ID 31 departs six minutes after timestamp t. Bus ID 19 departs seven minutes after timestamp t. The only bus departures that matter are the listed bus IDs at their specific offsets from t. Those bus IDs can depart at other times, and other bus IDs can depart at those times. For example, in the list above, because bus ID 19 must depart seven minutes after the timestamp at which bus ID 7 departs, bus ID 7 will always also be departing with bus ID 19 at seven minutes after timestamp t. In this example, the earliest timestamp at which this occurs is 1068781: time bus 7 bus 13 bus 59 bus 31 bus 19 1068773 . . . . . 1068774 D . . . . 1068775 . . . . . 1068776 . . . . . 1068777 . . . . . 1068778 . . . . . 1068779 . . . . . 1068780 . . . . . 1068781 D . . . . 1068782 . D . . . 1068783 . . . . . 1068784 . . . . . 1068785 . . D . . 1068786 . . . . . 1068787 . . . D . 1068788 D . . . D 1068789 . . . . . 1068790 . . . . . 1068791 . . . . . 1068792 . . . . . 1068793 . . . . . 1068794 . . . . . 1068795 D D . . . 1068796 . . . . . 1068797 . . . . . In the above example, bus ID 7 departs at timestamp 1068788 (seven minutes after t). This is fine; the only requirement on that minute is that bus ID 19 departs then, and it does. Here are some other examples: The earliest timestamp that matches the list 17,x,13,19 is 3417. 67,7,59,61 first occurs at timestamp 754018. 67,x,7,59,61 first occurs at timestamp 779210. 67,7,x,59,61 first occurs at timestamp 1261476. 1789,37,47,1889 first occurs at timestamp 1202161486. However, with so many bus IDs in your list, surely the actual earliest timestamp will be larger than 100000000000000! What is the earliest timestamp such that all of the listed bus IDs depart at offsets matching their positions in the list?
253
--- Day 7: No Space Left On Device --- You can hear birds chirping and raindrops hitting leaves as the expedition proceeds. Occasionally, you can even hear much louder sounds in the distance; how big do the animals get out here, anyway? The device the Elves gave you has problems with more than just its communication system. You try to run a system update: $ system-update --please --pretty-please-with-sugar-on-top Error: No space left on device Perhaps you can delete some files to make space for the update? You browse around the filesystem to assess the situation and save the resulting terminal output (your puzzle input). For example: $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k The filesystem consists of a tree of files (plain data) and directories (which can contain other directories or files). The outermost directory is called /. You can navigate around the filesystem, moving into or out of directories and listing the contents of the directory you're currently in. Within the terminal output, lines that begin with $ are commands you executed, very much like some modern computers: cd means change directory. This changes which directory is the current directory, but the specific result depends on the argument: cd x moves in one level: it looks in the current directory for the directory named x and makes it the current directory. cd .. moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory. cd / switches the current directory to the outermost directory, /. ls means list. It prints out all of the files and directories immediately contained by the current directory: 123 abc means that the current directory contains a file named abc with size 123. dir xyz means that the current directory contains a directory named xyz. Given the commands and output in the example above, you can determine that the filesystem looks visually like this: - / (dir) - a (dir) - e (dir) - i (file, size=584) - f (file, size=29116) - g (file, size=2557) - h.lst (file, size=62596) - b.txt (file, size=14848514) - c.dat (file, size=8504156) - d (dir) - j (file, size=4060174) - d.log (file, size=8033020) - d.ext (file, size=5626152) - k (file, size=7214296) Here, there are four directories: / (the outermost directory), a and d (which are in /), and e (which is in a). These directories also contain files of various sizes. Since the disk is full, your first step should probably be to find directories that are good candidates for deletion. To do this, you need to determine the total size of each directory. The total size of a directory is the sum of the sizes of the files it contains, directly or indirectly. (Directories themselves do not count as having any intrinsic size.) The total sizes of the directories above can be found as follows: The total size of directory e is 584 because it contains a single file i of size 584 and no other directories. The directory a has total size 94853 because it contains files f (size 29116), g (size 2557), and h.lst (size 62596), plus file i indirectly (a contains e which contains i). Directory d has total size 24933642. As the outermost directory, / contains every file. Its total size is 48381165, the sum of the size of every file. To begin, find all of the directories with a total size of at most 100000, then calculate the sum of their total sizes. In the example above, these directories are a and e; the sum of their total sizes is 95437 (94853 + 584). (As in this example, this process can count files more than once!) Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories? Your puzzle answer was 1642503. --- Part Two --- Now, you're ready to choose a directory to delete. The total disk space available to the filesystem is 70000000. To run the update, you need unused space of at least 30000000. You need to find a directory you can delete that will free up enough space to run the update. In the example above, the total size of the outermost directory (and thus the total amount of used space) is 48381165; this means that the size of the unused space must currently be 21618835, which isn't quite the 30000000 required by the update. Therefore, the update still requires a directory with total size of at least 8381165 to be deleted before it can run. To achieve this, you have the following options: Delete directory e, which would increase unused space by 584. Delete directory a, which would increase unused space by 94853. Delete directory d, which would increase unused space by 24933642. Delete directory /, which would increase unused space by 48381165. Directories e and a are both too small; deleting them would not free up enough space. However, directories d and / are both big enough! Between these, choose the smallest: d, increasing unused space by 24933642. Find the smallest directory that, if deleted, would free up enough space on the filesystem to run the update. What is the total size of that directory?
254
--- Day 11: Dumbo Octopus --- You enter a large cavern full of rare bioluminescent dumbo octopuses! They seem to not like the Christmas lights on your submarine, so you turn them off for now. There are 100 octopuses arranged neatly in a 10 by 10 grid. Each octopus slowly gains energy over time and flashes brightly for a moment when its energy is full. Although your lights are off, maybe you could navigate through the cave without disturbing the octopuses if you could predict when the flashes of light will happen. Each octopus has an energy level - your submarine can remotely measure the energy level of each octopus (your puzzle input). For example: 5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 The energy level of each octopus is a value between 0 and 9. Here, the top-left octopus has an energy level of 5, the bottom-right one has an energy level of 6, and so on. You can model the energy levels and flashes of light in steps. During a single step, the following occurs: First, the energy level of each octopus increases by 1. Then, any octopus with an energy level greater than 9 flashes. This increases the energy level of all adjacent octopuses by 1, including octopuses that are diagonally adjacent. If this causes an octopus to have an energy level greater than 9, it also flashes. This process continues as long as new octopuses keep having their energy level increased beyond 9. (An octopus can only flash at most once per step.) Finally, any octopus that flashed during this step has its energy level set to 0, as it used all of its energy to flash. Adjacent flashes can cause an octopus to flash on a step even if it begins that step with very little energy. Consider the middle octopus with 1 energy in this situation: Before any steps: 11111 19991 19191 19991 11111 After step 1: 34543 40004 50005 40004 34543 After step 2: 45654 51115 61116 51115 45654 An octopus is highlighted when it flashed during the given step. Here is how the larger example above progresses: Before any steps: 5483143223 2745854711 5264556173 6141336146 6357385478 4167524645 2176841721 6882881134 4846848554 5283751526 After step 1: 6594254334 3856965822 6375667284 7252447257 7468496589 5278635756 3287952832 7993992245 5957959665 6394862637 After step 2: 8807476555 5089087054 8597889608 8485769600 8700908800 6600088989 6800005943 0000007456 9000000876 8700006848 After step 3: 0050900866 8500800575 9900000039 9700000041 9935080063 7712300000 7911250009 2211130000 0421125000 0021119000 After step 4: 2263031977 0923031697 0032221150 0041111163 0076191174 0053411122 0042361120 5532241122 1532247211 1132230211 After step 5: 4484144000 2044144000 2253333493 1152333274 1187303285 1164633233 1153472231 6643352233 2643358322 2243341322 After step 6: 5595255111 3155255222 3364444605 2263444496 2298414396 2275744344 2264583342 7754463344 3754469433 3354452433 After step 7: 6707366222 4377366333 4475555827 3496655709 3500625609 3509955566 3486694453 8865585555 4865580644 4465574644 After step 8: 7818477333 5488477444 5697666949 4608766830 4734946730 4740097688 6900007564 0000009666 8000004755 6800007755 After step 9: 9060000644 7800000976 6900000080 5840000082 5858000093 6962400000 8021250009 2221130009 9111128097 7911119976 After step 10: 0481112976 0031112009 0041112504 0081111406 0099111306 0093511233 0442361130 5532252350 0532250600 0032240000 After step 10, there have been a total of 204 flashes. Fast forwarding, here is the same configuration every 10 steps: After step 20: 3936556452 5686556806 4496555690 4448655580 4456865570 5680086577 7000009896 0000000344 6000000364 4600009543 After step 30: 0643334118 4253334611 3374333458 2225333337 2229333338 2276733333 2754574565 5544458511 9444447111 7944446119 After step 40: 6211111981 0421111119 0042111115 0003111115 0003111116 0065611111 0532351111 3322234597 2222222976 2222222762 After step 50: 9655556447 4865556805 4486555690 4458655580 4574865570 5700086566 6000009887 8000000533 6800000633 5680000538 After step 60: 2533334200 2743334640 2264333458 2225333337 2225333338 2287833333 3854573455 1854458611 1175447111 1115446111 After step 70: 8211111164 0421111166 0042111114 0004211115 0000211116 0065611111 0532351111 7322235117 5722223475 4572222754 After step 80: 1755555697 5965555609 4486555680 4458655580 4570865570 5700086566 7000008666 0000000990 0000000800 0000000000 After step 90: 7433333522 2643333522 2264333458 2226433337 2222433338 2287833333 2854573333 4854458333 3387779333 3333333333 After step 100: 0397666866 0749766918 0053976933 0004297822 0004229892 0053222877 0532222966 9322228966 7922286866 6789998766 After 100 steps, there have been a total of 1656 flashes. Given the starting energy levels of the dumbo octopuses in your cavern, simulate 100 steps. How many total flashes are there after 100 steps? Your puzzle answer was 1757. --- Part Two --- It seems like the individual flashes aren't bright enough to navigate. However, you might have a better option: the flashes seem to be synchronizing! In the example above, the first time all octopuses flash simultaneously is step 195: After step 193: 5877777777 8877777777 7777777777 7777777777 7777777777 7777777777 7777777777 7777777777 7777777777 7777777777 After step 194: 6988888888 9988888888 8888888888 8888888888 8888888888 8888888888 8888888888 8888888888 8888888888 8888888888 After step 195: 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 0000000000 If you can calculate the exact moments when the octopuses will all flash simultaneously, you should be able to navigate through the cavern. What is the first step during which all octopuses flash?
255
--- Day 23: LAN Party --- As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). The network map provides a list of every connection between two computers. For example: kh-tc qp-kh de-cg ka-co yn-aq qp-ub cg-tb vc-aq tb-ka wh-tc yn-cg kh-ub ta-co de-co tc-td tb-wq wh-td ta-ka td-qp aq-cg wq-ub ub-vc de-ta wq-aq wq-vc wh-yn ka-de kh-ta co-tc wh-qp tb-vc td-yn Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. In this example, there are 12 such sets of three inter-connected computers: aq,cg,yn aq,vc,wq co,de,ka co,de,ta co,ka,ta de,ka,ta kh,qp,ub qp,td,wh tb,vc,wq tc,td,wh td,wh,yn ub,vc,wq If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: co,de,ta co,ka,ta de,ka,ta qp,td,wh tb,vc,wq tc,td,wh td,wh,yn Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?
256
--- Day 16: Dragon Checksum --- You're done scanning this part of the network, but you've left traces of your presence. You need to overwrite some disks with random-looking data to cover your tracks and update the local security system with a new checksum for those disks. For the data to not be suspicious, it needs to have certain properties; purely random data will be detected as tampering. To generate appropriate random data, you'll need to use a modified dragon curve. Start with an appropriate initial state (your puzzle input). Then, so long as you don't have enough data yet to fill the disk, repeat the following steps: Call the data you have at this point "a". Make a copy of "a"; call this copy "b". Reverse the order of the characters in "b". In "b", replace all instances of 0 with 1 and all 1s with 0. The resulting data is "a", then a single 0, then "b". For example, after a single step of this process, 1 becomes 100. 0 becomes 001. 11111 becomes 11111000000. 111100001010 becomes 1111000010100101011110000. Repeat these steps until you have enough data to fill the desired disk. Once the data has been generated, you also need to create a checksum of that data. Calculate the checksum only for the data that fits on the disk, even if you generated more data than that in the previous step. The checksum for some given data is created by considering each non-overlapping pair of characters in the input data. If the two characters match (00 or 11), the next checksum character is a 1. If the characters do not match (01 or 10), the next checksum character is a 0. This should produce a new string which is exactly half as long as the original. If the length of the checksum is even, repeat the process until you end up with a checksum with an odd length. For example, suppose we want to fill a disk of length 12, and when we finally generate a string of at least length 12, the first 12 characters are 110010110100. To generate its checksum: Consider each pair: 11, 00, 10, 11, 01, 00. These are same, same, different, same, different, same, producing 110101. The resulting string has length 6, which is even, so we repeat the process. The pairs are 11 (same), 01 (different), 01 (different). This produces the checksum 100, which has an odd length, so we stop. Therefore, the checksum for 110010110100 is 100. Combining all of these steps together, suppose you want to fill a disk of length 20 using an initial state of 10000: Because 10000 is too short, we first use the modified dragon curve to make it longer. After one round, it becomes 10000011110 (11 characters), still too short. After two rounds, it becomes 10000011110010000111110 (23 characters), which is enough. Since we only need 20, but we have 23, we get rid of all but the first 20 characters: 10000011110010000111. Next, we start calculating the checksum; after one round, we have 0111110101, which 10 characters long (even), so we continue. After two rounds, we have 01100, which is 5 characters long (odd), so we are done. In this example, the correct checksum would therefore be 01100. The first disk you have to fill has length 272. Using the initial state in your puzzle input, what is the correct checksum? Your puzzle answer was 10100011010101011. --- Part Two --- The second disk you have to fill has length 35651584. Again using the initial state in your puzzle input, what is the correct checksum for this disk?
257
--- Day 3: Gear Ratios --- You and the Elf eventually reach a gondola lift station; he says the gondola lift will take you up to the water source, but this is as far as he can bring you. You go inside. It doesn't take long to find the gondolas, but there seems to be a problem: they're not moving. "Aaah!" You turn around to see a slightly-greasy Elf with a wrench and a look of surprise. "Sorry, I wasn't expecting anyone! The gondola lift isn't working right now; it'll still be a while before I can fix it." You offer to help. The engineer explains that an engine part seems to be missing from the engine, but nobody can figure out which one. If you can add up all the part numbers in the engine schematic, it should be easy to work out which part is missing. The engine schematic (your puzzle input) consists of a visual representation of the engine. There are lots of numbers and symbols you don't really understand, but apparently any number adjacent to a symbol, even diagonally, is a "part number" and should be included in your sum. (Periods (.) do not count as a symbol.) Here is an example engine schematic: 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. In this schematic, two numbers are not part numbers because they are not adjacent to a symbol: 114 (top right) and 58 (middle right). Every other number is adjacent to a symbol and so is a part number; their sum is 4361. Of course, the actual engine schematic is much larger. What is the sum of all of the part numbers in the engine schematic? Your puzzle answer was 546563. --- Part Two --- The engineer finds the missing part and installs it in the engine! As the engine springs to life, you jump in the closest gondola, finally ready to ascend to the water source. You don't seem to be going very fast, though. Maybe something is still wrong? Fortunately, the gondola has a phone labeled "help", so you pick it up and the engineer answers. Before you can explain the situation, she suggests that you look out the window. There stands the engineer, holding a phone in one hand and waving with the other. You're going so slowly that you haven't even left the station. You exit the gondola. The missing part wasn't the only issue - one of the gears in the engine is wrong. A gear is any * symbol that is adjacent to exactly two part numbers. Its gear ratio is the result of multiplying those two numbers together. This time, you need to find the gear ratio of every gear and add them all up so that the engineer can figure out which gear needs to be replaced. Consider the same engine schematic again: 467..114.. ...*...... ..35..633. ......#... 617*...... .....+.58. ..592..... ......755. ...$.*.... .664.598.. In this schematic, there are two gears. The first is in the top left; it has part numbers 467 and 35, so its gear ratio is 16345. The second gear is in the lower right; its gear ratio is 451490. (The * adjacent to 617 is not a gear because it is only adjacent to one part number.) Adding up all of the gear ratios produces 467835. What is the sum of all of the gear ratios in your engine schematic?
258
--- Day 4: The Ideal Stocking Stuffer --- Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys. To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 hash is some secret key (your puzzle input, given below) followed by a number in decimal. To mine AdventCoins, you must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) that produces such a hash. For example: If your secret key is abcdef, the answer is 609043, because the MD5 hash of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the lowest such number to do so. If your secret key is pqrstuv, the lowest number it combines with to make an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of pqrstuv1048970 looks like 000006136ef....
259
--- Day 17: Set and Forget --- An early warning system detects an incoming solar flare and automatically activates the ship's electromagnetic shield. Unfortunately, this has cut off the Wi-Fi for many small robots that, unaware of the impending danger, are now trapped on exterior scaffolding on the unsafe side of the shield. To rescue them, you'll have to act quickly! The only tools at your disposal are some wired cameras and a small vacuum robot currently asleep at its charging station. The video quality is poor, but the vacuum robot has a needlessly bright LED that makes it easy to spot no matter where it is. An Intcode program, the Aft Scaffolding Control and Information Interface (ASCII, your puzzle input), provides access to the cameras and the vacuum robot. Currently, because the vacuum robot is asleep, you can only access the cameras. Running the ASCII program on your Intcode computer will provide the current view of the scaffolds. This is output, purely coincidentally, as ASCII code: 35 means #, 46 means ., 10 starts a new line of output below the current one, and so on. (Within a line, characters are drawn left-to-right.) In the camera output, # represents a scaffold and . represents open space. The vacuum robot is visible as ^, v, <, or > depending on whether it is facing up, down, left, or right respectively. When drawn like this, the vacuum robot is always on a scaffold; if the vacuum robot ever walks off of a scaffold and begins tumbling through space uncontrollably, it will instead be visible as X. In general, the scaffold forms a path, but it sometimes loops back onto itself. For example, suppose you can see the following view from the cameras: ..#.......... ..#.......... #######...### #.#...#...#.# ############# ..#...#...#.. ..#####...^.. Here, the vacuum robot, ^ is facing up and sitting at one end of the scaffold near the bottom-right of the image. The scaffold continues up, loops across itself several times, and ends at the top-left of the image. The first step is to calibrate the cameras by getting the alignment parameters of some well-defined points. Locate all scaffold intersections; for each, its alignment parameter is the distance between its left edge and the left edge of the view multiplied by the distance between its top edge and the top edge of the view. Here, the intersections from the above image are marked O: ..#.......... ..#.......... ##O####...### #.#...#...#.# ##O###O###O## ..#...#...#.. ..#####...^.. For these intersections: The top-left intersection is 2 units from the left of the image and 2 units from the top of the image, so its alignment parameter is 2 * 2 = 4. The bottom-left intersection is 2 units from the left and 4 units from the top, so its alignment parameter is 2 * 4 = 8. The bottom-middle intersection is 6 from the left and 4 from the top, so its alignment parameter is 24. The bottom-right intersection's alignment parameter is 40. To calibrate the cameras, you need the sum of the alignment parameters. In the above example, this is 76. Run your ASCII program. What is the sum of the alignment parameters for the scaffold intersections? Your puzzle answer was 5948. --- Part Two --- Now for the tricky part: notifying all the other robots about the solar flare. The vacuum robot can do this automatically if it gets into range of a robot. However, you can't see the other robots on the camera, so you need to be thorough instead: you need to make the vacuum robot visit every part of the scaffold at least once. The vacuum robot normally wanders randomly, but there isn't time for that today. Instead, you can override its movement logic with new rules. Force the vacuum robot to wake up by changing the value in your ASCII program at address 0 from 1 to 2. When you do this, you will be automatically prompted for the new movement rules that the vacuum robot should use. The ASCII program will use input instructions to receive them, but they need to be provided as ASCII code; end each line of logic with a single newline, ASCII code 10. First, you will be prompted for the main movement routine. The main routine may only call the movement functions: A, B, or C. Supply the movement functions to use as ASCII text, separating them with commas (,, ASCII code 44), and ending the list with a newline (ASCII code 10). For example, to call A twice, then alternate between B and C three times, provide the string A,A,B,C,B,C,B,C and then a newline. Then, you will be prompted for each movement function. Movement functions may use L to turn left, R to turn right, or a number to move forward that many units. Movement functions may not call other movement functions. Again, separate the actions with commas and end the list with a newline. For example, to move forward 10 units, turn left, move forward 8 units, turn right, and finally move forward 6 units, provide the string 10,L,8,R,6 and then a newline. Finally, you will be asked whether you want to see a continuous video feed; provide either y or n and a newline. Enabling the continuous video feed can help you see what's going on, but it also requires a significant amount of processing power, and may even cause your Intcode computer to overheat. Due to the limited amount of memory in the vacuum robot, the ASCII definitions of the main routine and the movement functions may each contain at most 20 characters, not counting the newline. For example, consider the following camera feed: #######...##### #.....#...#...# #.....#...#...# ......#...#...# ......#...###.# ......#.....#.# ^########...#.# ......#.#...#.# ......######### ........#...#.. ....#########.. ....#...#...... ....#...#...... ....#...#...... ....#####...... In order for the vacuum robot to visit every part of the scaffold at least once, one path it could take is: R,8,R,8,R,4,R,4,R,8,L,6,L,2,R,4,R,4,R,8,R,8,R,8,L,6,L,2 Without the memory limit, you could just supply this whole string to function A and have the main routine call A once. However, you'll need to split it into smaller parts. One approach is: Main routine: A,B,C,B,A,C (ASCII input: 65, 44, 66, 44, 67, 44, 66, 44, 65, 44, 67, 10) Function A: R,8,R,8 (ASCII input: 82, 44, 56, 44, 82, 44, 56, 10) Function B: R,4,R,4,R,8 (ASCII input: 82, 44, 52, 44, 82, 44, 52, 44, 82, 44, 56, 10) Function C: L,6,L,2 (ASCII input: 76, 44, 54, 44, 76, 44, 50, 10) Visually, this would break the desired path into the following parts: A, B, C, B, A, C R,8,R,8, R,4,R,4,R,8, L,6,L,2, R,4,R,4,R,8, R,8,R,8, L,6,L,2 CCCCCCA...BBBBB C.....A...B...B C.....A...B...B ......A...B...B ......A...CCC.B ......A.....C.B ^AAAAAAAA...C.B ......A.A...C.B ......AAAAAA#AB ........A...C.. ....BBBB#BBBB.. ....B...A...... ....B...A...... ....B...A...... ....BBBBA...... Of course, the scaffolding outside your ship is much more complex. As the vacuum robot finds other robots and notifies them of the impending solar flare, it also can't help but leave them squeaky clean, collecting any space dust it finds. Once it finishes the programmed set of movements, assuming it hasn't drifted off into space, the cleaning robot will return to its docking station and report the amount of space dust it collected as a large, non-ASCII value in a single output instruction. After visiting every part of the scaffold at least once, how much dust does the vacuum robot report it has collected?
260
--- Day 8: Memory Maneuver --- The sleigh is much easier to pull than you'd expect for something its weight. Unfortunately, neither you nor the Elves know which way the North Pole is from here. You check your wrist device for anything that might help. It seems to have some kind of navigation system! Activating the navigation system produces more bad news: "Failed to start navigation system. Could not read software license file." The navigation system's license file consists of a list of numbers (your puzzle input). The numbers define a data structure which, when processed, produces some kind of tree that can be used to calculate the license number. The tree is made up of nodes; a single, outermost node forms the tree's root, and it contains all other nodes in the tree (or contains nodes that contain nodes, and so on). Specifically, a node consists of: A header, which is always exactly two numbers: The quantity of child nodes. The quantity of metadata entries. Zero or more child nodes (as specified in the header). One or more metadata entries (as specified in the header). Each child node is itself a node that has its own header, child nodes, and metadata. For example: 2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2 A---------------------------------- B----------- C----------- D----- In this example, each node of the tree is also marked with an underline starting with a letter for easier identification. In it, there are four nodes: A, which has 2 child nodes (B, C) and 3 metadata entries (1, 1, 2). B, which has 0 child nodes and 3 metadata entries (10, 11, 12). C, which has 1 child node (D) and 1 metadata entry (2). D, which has 0 child nodes and 1 metadata entry (99). The first check done on the license file is to simply add up all of the metadata entries. In this example, that sum is 1+1+2+10+11+12+2+99=138. What is the sum of all metadata entries?
261
--- Day 13: Mine Cart Madness --- A crop of this size requires significant logistics to transport produce, soil, fertilizer, and so on. The Elves are very busy pushing things around in carts on some kind of rudimentary system of tracks they've come up with. Seeing as how cart-and-track systems don't appear in recorded history for another 1000 years, the Elves seem to be making this up as they go along. They haven't even figured out how to avoid collisions yet. You map out the tracks (your puzzle input) and see where you can help. Tracks consist of straight paths (| and -), curves (/ and ), and intersections (+). Curves connect exactly two perpendicular pieces of track; for example, this is a closed loop: /----| | | | ----/ Intersections occur when two perpendicular paths cross. At an intersection, a cart is capable of turning left, turning right, or continuing straight. Here are two loops connected by two intersections: /-----| | | /--+--| | | | --+--/ | | | -----/ Several carts are also on the tracks. Carts always face either up (^), down (v), left (<), or right (>). (On your initial map, the track under each cart is a straight path matching the direction the cart is facing.) Each time a cart has the option to turn (by arriving at any intersection), it turns left the first time, goes straight the second time, turns right the third time, and then repeats those directions starting again with left the fourth time, straight the fifth time, and so on. This process is independent of the particular intersection at which the cart has arrived - that is, the cart has no per-intersection memory. Carts all move at the same speed; they take turns moving a single step at a time. They do this based on their current location: carts on the top row move first (acting from left to right), then carts on the second row move (again from left to right), then carts on the third row, and so on. Once each cart has moved one step, the process repeats; each of these loops is called a tick. For example, suppose there are two carts on a straight track: | | | | | v | | | | | v v | | | | | v X | | ^ ^ | ^ ^ | | | | | | | | First, the top cart moves. It is facing down (v), so it moves down one square. Second, the bottom cart moves. It is facing up (^), so it moves up one square. Because all carts have moved, the first tick ends. Then, the process repeats, starting with the first cart. The first cart moves down, then the second cart moves up - right into the first cart, colliding with it! (The location of the crash is marked with an X.) This ends the second and last tick. Here is a longer example: /->- | | /----| /-+--+- | | | | | v | -+-/ -+--/ ------/ /--> | | /----| /-+--+- | | | | | | | -+-/ ->--/ ------/ /---v | | /----| /-+--+- | | | | | | | -+-/ -+>-/ ------/ /--- | v /----| /-+--+- | | | | | | | -+-/ -+->/ ------/ /--- | | /----| /->--+- | | | | | | | -+-/ -+--^ ------/ /--- | | /----| /-+>-+- | | | | | | ^ -+-/ -+--/ ------/ /--- | | /----| /-+->+- ^ | | | | | | -+-/ -+--/ ------/ /--- | | /----< | /-+-->- | | | | | | | -+-/ -+--/ ------/ /--- | | /---<| /-+--+> | | | | | | | -+-/ -+--/ ------/ /--- | | /--<-| /-+--+-v | | | | | | | -+-/ -+--/ ------/ /--- | | /-<--| /-+--+- | | | | | v | -+-/ -+--/ ------/ /--- | | /<---| /-+--+- | | | | | | | -+-/ -<--/ ------/ /--- | | v----| /-+--+- | | | | | | | -+-/ <+--/ ------/ /--- | | /----| /-+--v- | | | | | | | -+-/ ^-+--/ ------/ /--- | | /----| /-+--+- | | | | X | | -+-/ -+--/ ------/ After following their respective paths for a while, the carts eventually crash. To help prevent crashes, you'd like to know the location of the first crash. Locations are given in X,Y coordinates, where the furthest left column is X=0 and the furthest top row is Y=0: 111 0123456789012 0/--- 1| | /----2| /-+--+- | 3| | | X | | 4-+-/ -+--/ 5 ------/ In this example, the location of the first crash is 7,3.
262
--- Day 16: The Floor Will Be Lava --- With the beam of light completely focused somewhere, the reindeer leads you deeper still into the Lava Production Facility. At some point, you realize that the steel facility walls have been replaced with cave, and the doorways are just cave, and the floor is cave, and you're pretty sure this is actually just a giant cave. Finally, as you approach what must be the heart of the mountain, you see a bright light in a cavern up ahead. There, you discover that the beam of light you so carefully focused is emerging from the cavern wall closest to the facility and pouring all of its energy into a contraption on the opposite side. Upon closer inspection, the contraption appears to be a flat, two-dimensional square grid containing empty space (.), mirrors (/ and ), and splitters (| and -). The contraption is aligned so that most of the beam bounces around the grid, but each tile on the grid converts some of the beam's light into heat to melt the rock in the cavern. You note the layout of the contraption (your puzzle input). For example: .|....... |.-...... .....|-... ........|. .......... ............./.\.. .-.-/..|.. .|....-|...//.|.... The beam enters in the top-left corner from the left and heading to the right. Then, its behavior depends on what it encounters as it moves: If the beam encounters empty space (.), it continues in the same direction. If the beam encounters a mirror (/ or ), the beam is reflected 90 degrees depending on the angle of the mirror. For instance, a rightward-moving beam that encounters a / mirror would continue upward in the mirror's column, while a rightward-moving beam that encounters a mirror would continue downward from the mirror's column. If the beam encounters the pointy end of a splitter (| or -), the beam passes through the splitter as if the splitter were empty space. For instance, a rightward-moving beam that encounters a - splitter would continue in the same direction. If the beam encounters the flat side of a splitter (| or -), the beam is split into two beams going in each of the two directions the splitter's pointy ends are pointing. For instance, a rightward-moving beam that encounters a | splitter would split into two beams: one that continues upward from the splitter's column and one that continues downward from the splitter's column. Beams do not interact with other beams; a tile can have many beams passing through it at the same time. A tile is energized if that tile has at least one beam pass through it, reflect in it, or split in it. In the above example, here is how the beam of light bounces around the contraption: >|<<<.... |v-.^.... .v...|->>> .v...v^.|. .v...v^... .v...v^...v../2\.. <->-/vv|.. .|<<<2-|..v//.|.v.. Beams are only shown on empty tiles; arrows indicate the direction of the beams. If a tile contains beams moving in multiple directions, the number of distinct directions is shown instead. Here is the same diagram but instead only showing whether a tile is energized (#) or not (.): ######.... .#...#.... .#...##### .#...##... .#...##... .#...##... .#..####.. ########.. .#######.. .#...#.#.. Ultimately, in this example, 46 tiles become energized. The light isn't energizing enough tiles to produce lava; to debug the contraption, you need to start by analyzing the current situation. With the beam starting in the top-left heading right, how many tiles end up being energized?
263
--- Day 11: Space Police --- On the way to Jupiter, you're pulled over by the Space Police. "Attention, unmarked spacecraft! You are in violation of Space Law! All spacecraft must have a clearly visible registration identifier! You have 24 hours to comply or be sent to Space Jail!" Not wanting to be sent to Space Jail, you radio back to the Elves on Earth for help. Although it takes almost three hours for their reply signal to reach you, they send instructions for how to power up the emergency hull painting robot and even provide a small Intcode program (your puzzle input) that will cause it to paint your ship appropriately. There's just one problem: you don't have an emergency hull painting robot. You'll need to build a new emergency hull painting robot. The robot needs to be able to move around on the grid of square panels on the side of your ship, detect the color of its current panel, and paint its current panel black or white. (All of the panels are currently black.) The Intcode program will serve as the brain of the robot. The program uses input instructions to access the robot's camera: provide 0 if the robot is over a black panel or 1 if the robot is over a white panel. Then, the program will output two values: First, it will output a value indicating the color to paint the panel the robot is over: 0 means to paint the panel black, and 1 means to paint the panel white. Second, it will output a value indicating the direction the robot should turn: 0 means it should turn left 90 degrees, and 1 means it should turn right 90 degrees. After the robot turns, it should always move forward exactly one panel. The robot starts facing up. The robot will continue running for a while like this and halt when it is finished drawing. Do not restart the Intcode computer inside the robot during this process. For example, suppose the robot is about to start running. Drawing black panels as ., white panels as #, and the robot pointing the direction it is facing (< ^ > v), the initial state and region near the robot looks like this: ..... ..... ..^.. ..... ..... The panel under the robot (not visible here because a ^ is shown instead) is also black, and so any input instructions at this point should be provided 0. Suppose the robot eventually outputs 1 (paint white) and then 0 (turn left). After taking these actions and moving forward one panel, the region now looks like this: ..... ..... .<#.. ..... ..... Input instructions should still be provided 0. Next, the robot might output 0 (paint black) and then 0 (turn left): ..... ..... ..#.. .v... ..... After more outputs (1,0, 1,0): ..... ..... ..^.. .##.. ..... The robot is now back where it started, but because it is now on a white panel, input instructions should be provided 1. After several more outputs (0,1, 1,0, 1,0), the area looks like this: ..... ..<#. ...#. .##.. ..... Before you deploy the robot, you should probably have an estimate of the area it will cover: specifically, you need to know the number of panels it paints at least once, regardless of color. In the example above, the robot painted 6 panels at least once. (It painted its starting panel twice, but that panel is still only counted once; it also never painted the panel it ended on.) Build a new emergency hull painting robot and run the Intcode program on it. How many panels does it paint at least once?
264
--- Day 19: Aplenty --- The Elves of Gear Island are thankful for your help and send you on your way. They even have a hang glider that someone stole from Desert Island; since you're already going that direction, it would help them a lot if you would use it to get down there and return it to them. As you reach the bottom of the relentless avalanche of machine parts, you discover that they're already forming a formidable heap. Don't worry, though - a group of Elves is already here organizing the parts, and they have a system. To start, each part is rated in each of four categories: x: Extremely cool looking m: Musical (it makes a noise when you hit it) a: Aerodynamic s: Shiny Then, each part is sent through a series of workflows that will ultimately accept or reject the part. Each workflow has a name and contains a list of rules; each rule specifies a condition and where to send the part if the condition is true. The first rule that matches the part being considered is applied immediately, and the part moves on to the destination described by the rule. (The last rule in each workflow has no condition and always applies if reached.) Consider the workflow ex{x>10:one,m<20:two,a>30:R,A}. This workflow is named ex and contains four rules. If workflow ex were considering a specific part, it would perform the following steps in order: Rule "x>10:one": If the part's x is more than 10, send the part to the workflow named one. Rule "m<20:two": Otherwise, if the part's m is less than 20, send the part to the workflow named two. Rule "a>30:R": Otherwise, if the part's a is more than 30, the part is immediately rejected (R). Rule "A": Otherwise, because no other rules matched the part, the part is immediately accepted (A). If a part is sent to another workflow, it immediately switches to the start of that workflow instead and never returns. If a part is accepted (sent to A) or rejected (sent to R), the part immediately stops any further processing. The system works, but it's not keeping up with the torrent of weird metal shapes. The Elves ask if you can help sort a few parts and give you the list of workflows and some part ratings (your puzzle input). For example: px{a<2006:qkq,m>2090:A,rfg} pv{a>1716:R,A} lnx{m>1548:A,A} rfg{s<537:gd,x>2440:R,A} qs{s>3448:A,lnx} qkq{x<1416:A,crn} crn{x>2662:A,R} in{s<1351:px,qqz} qqz{s>2770:qs,m<1801:hdj,R} gd{a>3333:R,R} hdj{m>838:A,pv} {x=787,m=2655,a=1222,s=2876} {x=1679,m=44,a=2067,s=496} {x=2036,m=264,a=79,s=2244} {x=2461,m=1339,a=466,s=291} {x=2127,m=1623,a=2188,s=1013} The workflows are listed first, followed by a blank line, then the ratings of the parts the Elves would like you to sort. All parts begin in the workflow named in. In this example, the five listed parts go through the following workflows: {x=787,m=2655,a=1222,s=2876}: in -> qqz -> qs -> lnx -> A {x=1679,m=44,a=2067,s=496}: in -> px -> rfg -> gd -> R {x=2036,m=264,a=79,s=2244}: in -> qqz -> hdj -> pv -> A {x=2461,m=1339,a=466,s=291}: in -> px -> qkq -> crn -> R {x=2127,m=1623,a=2188,s=1013}: in -> px -> rfg -> A Ultimately, three parts are accepted. Adding up the x, m, a, and s rating for each of the accepted parts gives 7540 for the part with x=787, 4623 for the part with x=2036, and 6951 for the part with x=2127. Adding all of the ratings for all of the accepted parts gives the sum total of 19114. Sort through all of the parts you've been given; what do you get if you add together all of the rating numbers for all of the parts that ultimately get accepted?
265
--- Day 4: Passport Processing --- You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extremely similar, North Pole Credentials aren't issued by a country and therefore aren't actually valid documentation for travel in most of the world. It seems like you're not the only one having problems, though; a very long line has formed for the automatic passport scanners, and the delay could upset your travel itinerary. Due to some questionable network security, you realize you might be able to solve both of these problems at the same time. The automatic passport scanners are slow because they're having trouble detecting which passports have all required fields. The expected fields are as follows: byr (Birth Year) iyr (Issue Year) eyr (Expiration Year) hgt (Height) hcl (Hair Color) ecl (Eye Color) pid (Passport ID) cid (Country ID) Passport data is validated in batch files (your puzzle input). Each passport is represented as a sequence of key:value pairs separated by spaces or newlines. Passports are separated by blank lines. Here is an example batch file containing four passports: ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in The first passport is valid - all eight fields are present. The second passport is invalid - it is missing hgt (the Height field). The third passport is interesting; the only missing field is cid, so it looks like data from North Pole Credentials, not a passport at all! Surely, nobody would mind if you made the system temporarily ignore missing cid fields. Treat this "passport" as valid. The fourth passport is missing two fields, cid and byr. Missing cid is fine, but missing any other field is not, so this passport is invalid. According to the above rules, your improved system would report 2 valid passports. Count the number of valid passports - those that have all required fields. Treat cid as optional. In your batch file, how many passports are valid?
266
--- Day 10: Cathode-Ray Tube --- You avoid the ropes, plunge into the river, and swim to shore. The Elves yell something about meeting back up with them upriver, but the river is too loud to tell exactly what they're saying. They finish crossing the bridge and disappear from view. Situations like this must be why the Elves prioritized getting the communication system on your handheld device working. You pull it out of your pack, but the amount of water slowly draining from a big crack in its screen tells you it probably won't be of much immediate use. Unless, that is, you can design a replacement for the device's video system! It seems to be some kind of cathode-ray tube screen and simple CPU that are both driven by a precise clock circuit. The clock circuit ticks at a constant rate; each tick is called a cycle. Start by figuring out the signal being sent by the CPU. The CPU has a single register, X, which starts with the value 1. It supports only two instructions: addx V takes two cycles to complete. After two cycles, the X register is increased by the value V. (V can be negative.) noop takes one cycle to complete. It has no other effect. The CPU uses these instructions in a program (your puzzle input) to, somehow, tell the screen what to draw. Consider the following small program: noop addx 3 addx -5 Execution of this program proceeds as follows: At the start of the first cycle, the noop instruction begins execution. During the first cycle, X is 1. After the first cycle, the noop instruction finishes execution, doing nothing. At the start of the second cycle, the addx 3 instruction begins execution. During the second cycle, X is still 1. During the third cycle, X is still 1. After the third cycle, the addx 3 instruction finishes execution, setting X to 4. At the start of the fourth cycle, the addx -5 instruction begins execution. During the fourth cycle, X is still 4. During the fifth cycle, X is still 4. After the fifth cycle, the addx -5 instruction finishes execution, setting X to -1. Maybe you can learn something by looking at the value of the X register throughout execution. For now, consider the signal strength (the cycle number multiplied by the value of the X register) during the 20th cycle and every 40 cycles after that (that is, during the 20th, 60th, 100th, 140th, 180th, and 220th cycles). For example, consider this larger program: addx 15 addx -11 addx 6 addx -3 addx 5 addx -1 addx -8 addx 13 addx 4 noop addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx -35 addx 1 addx 24 addx -19 addx 1 addx 16 addx -11 noop noop addx 21 addx -15 noop noop addx -3 addx 9 addx 1 addx -3 addx 8 addx 1 addx 5 noop noop noop noop noop addx -36 noop addx 1 addx 7 noop noop noop addx 2 addx 6 noop noop noop noop noop addx 1 noop noop addx 7 addx 1 noop addx -13 addx 13 addx 7 noop addx 1 addx -33 noop noop noop addx 2 noop noop noop addx 8 noop addx -1 addx 2 addx 1 noop addx 17 addx -9 addx 1 addx 1 addx -3 addx 11 noop noop addx 1 noop addx 1 noop noop addx -13 addx -19 addx 1 addx 3 addx 26 addx -30 addx 12 addx -1 addx 3 addx 1 noop noop noop addx -9 addx 18 addx 1 addx 2 noop noop addx 9 noop noop noop addx -1 addx 2 addx -37 addx 1 addx 3 noop addx 15 addx -21 addx 22 addx -6 addx 1 noop addx 2 addx 1 noop addx -10 noop noop addx 20 addx 1 addx 2 addx 2 addx -6 addx -11 noop noop noop The interesting signal strengths can be determined as follows: During the 20th cycle, register X has the value 21, so the signal strength is 20 * 21 = 420. (The 20th cycle occurs in the middle of the second addx -1, so the value of register X is the starting value, 1, plus all of the other addx values up to that point: 1 + 15 - 11 + 6 - 3 + 5 - 1 - 8 + 13 + 4 = 21.) During the 60th cycle, register X has the value 19, so the signal strength is 60 * 19 = 1140. During the 100th cycle, register X has the value 18, so the signal strength is 100 * 18 = 1800. During the 140th cycle, register X has the value 21, so the signal strength is 140 * 21 = 2940. During the 180th cycle, register X has the value 16, so the signal strength is 180 * 16 = 2880. During the 220th cycle, register X has the value 18, so the signal strength is 220 * 18 = 3960. The sum of these signal strengths is 13140. Find the signal strength during the 20th, 60th, 100th, 140th, 180th, and 220th cycles. What is the sum of these six signal strengths? Your puzzle answer was 12740. --- Part Two --- It seems like the X register controls the horizontal position of a sprite. Specifically, the sprite is 3 pixels wide, and the X register sets the horizontal position of the middle of that sprite. (In this system, there is no such thing as "vertical position": if the sprite's horizontal position puts its pixels where the CRT is currently drawing, then those pixels will be drawn.) You count the pixels on the CRT: 40 wide and 6 high. This CRT screen draws the top row of pixels left-to-right, then the row below that, and so on. The left-most pixel in each row is in position 0, and the right-most pixel in each row is in position 39. Like the CPU, the CRT is tied closely to the clock circuit: the CRT draws a single pixel during each cycle. Representing each pixel of the screen as a #, here are the cycles during which the first and last pixel in each row are drawn: Cycle 1 -> ######################################## <- Cycle 40 Cycle 41 -> ######################################## <- Cycle 80 Cycle 81 -> ######################################## <- Cycle 120 Cycle 121 -> ######################################## <- Cycle 160 Cycle 161 -> ######################################## <- Cycle 200 Cycle 201 -> ######################################## <- Cycle 240 So, by carefully timing the CPU instructions and the CRT drawing operations, you should be able to determine whether the sprite is visible the instant each pixel is drawn. If the sprite is positioned such that one of its three pixels is the pixel currently being drawn, the screen produces a lit pixel (#); otherwise, the screen leaves the pixel dark (.). The first few pixels from the larger example above are drawn as follows: Sprite position: ###..................................... Start cycle 1: begin executing addx 15 During cycle 1: CRT draws pixel in position 0 Current CRT row: # During cycle 2: CRT draws pixel in position 1 Current CRT row: ## End of cycle 2: finish executing addx 15 (Register X is now 16) Sprite position: ...............###...................... Start cycle 3: begin executing addx -11 During cycle 3: CRT draws pixel in position 2 Current CRT row: ##. During cycle 4: CRT draws pixel in position 3 Current CRT row: ##.. End of cycle 4: finish executing addx -11 (Register X is now 5) Sprite position: ....###................................. Start cycle 5: begin executing addx 6 During cycle 5: CRT draws pixel in position 4 Current CRT row: ##..# During cycle 6: CRT draws pixel in position 5 Current CRT row: ##..## End of cycle 6: finish executing addx 6 (Register X is now 11) Sprite position: ..........###........................... Start cycle 7: begin executing addx -3 During cycle 7: CRT draws pixel in position 6 Current CRT row: ##..##. During cycle 8: CRT draws pixel in position 7 Current CRT row: ##..##.. End of cycle 8: finish executing addx -3 (Register X is now 8) Sprite position: .......###.............................. Start cycle 9: begin executing addx 5 During cycle 9: CRT draws pixel in position 8 Current CRT row: ##..##..# During cycle 10: CRT draws pixel in position 9 Current CRT row: ##..##..## End of cycle 10: finish executing addx 5 (Register X is now 13) Sprite position: ............###......................... Start cycle 11: begin executing addx -1 During cycle 11: CRT draws pixel in position 10 Current CRT row: ##..##..##. During cycle 12: CRT draws pixel in position 11 Current CRT row: ##..##..##.. End of cycle 12: finish executing addx -1 (Register X is now 12) Sprite position: ...........###.......................... Start cycle 13: begin executing addx -8 During cycle 13: CRT draws pixel in position 12 Current CRT row: ##..##..##..# During cycle 14: CRT draws pixel in position 13 Current CRT row: ##..##..##..## End of cycle 14: finish executing addx -8 (Register X is now 4) Sprite position: ...###.................................. Start cycle 15: begin executing addx 13 During cycle 15: CRT draws pixel in position 14 Current CRT row: ##..##..##..##. During cycle 16: CRT draws pixel in position 15 Current CRT row: ##..##..##..##.. End of cycle 16: finish executing addx 13 (Register X is now 17) Sprite position: ................###..................... Start cycle 17: begin executing addx 4 During cycle 17: CRT draws pixel in position 16 Current CRT row: ##..##..##..##..# During cycle 18: CRT draws pixel in position 17 Current CRT row: ##..##..##..##..## End of cycle 18: finish executing addx 4 (Register X is now 21) Sprite position: ....................###................. Start cycle 19: begin executing noop During cycle 19: CRT draws pixel in position 18 Current CRT row: ##..##..##..##..##. End of cycle 19: finish executing noop Start cycle 20: begin executing addx -1 During cycle 20: CRT draws pixel in position 19 Current CRT row: ##..##..##..##..##.. During cycle 21: CRT draws pixel in position 20 Current CRT row: ##..##..##..##..##..# End of cycle 21: finish executing addx -1 (Register X is now 20) Sprite position: ...................###.................. Allowing the program to run to completion causes the CRT to produce the following image: ##..##..##..##..##..##..##..##..##..##.. ###...###...###...###...###...###...###. ####....####....####....####....####.... #####.....#####.....#####.....#####..... ######......######......######......#### #######.......#######.......#######..... Render the image given by your program. What eight capital letters appear on your CRT?
267
--- Day 18: Many-Worlds Interpretation --- As you approach Neptune, a planetary security system detects you and activates a giant tractor beam on Triton! You have no choice but to land. A scan of the local area reveals only one interesting feature: a massive underground vault. You generate a map of the tunnels (your puzzle input). The tunnels are too narrow to move diagonally. Only one entrance (marked @) is present among the open passages (marked .) and stone walls (#), but you also detect an assortment of keys (shown as lowercase letters) and doors (shown as uppercase letters). Keys of a given letter open the door of the same letter: a opens A, b opens B, and so on. You aren't sure which key you need to disable the tractor beam, so you'll need to collect all of them. For example, suppose you have the following map: ######### #[email protected]# ######### Starting from the entrance (@), you can only access a large door (A) and a key (a). Moving toward the door doesn't help you, but you can move 2 steps to collect the key, unlocking A in the process: ######### #b.....@# ######### Then, you can move 6 steps to collect the only other key, b: ######### #@......# ######### So, collecting every key took a total of 8 steps. Here is a larger example: ######################## #[email protected].# ######################.# #d.....................# ######################## The only reasonable move is to take key a and unlock door A: ######################## #[email protected].# ######################.# #d.....................# ######################## Then, do the same with key b: ######################## #[email protected].# ######################.# #d.....................# ######################## ...and the same with key c: ######################## #f.D.E.e.............@.# ######################.# #d.....................# ######################## Now, you have a choice between keys d and e. While key e is closer, collecting it now would be slower in the long run than collecting key d first, so that's the best choice: ######################## #f...E.e...............# ######################.# #@.....................# ######################## Finally, collect key e to unlock door E, then collect key f, taking a grand total of 86 steps. Here are a few more examples: ######################## #...............b.C.D.f# #.###################### #[email protected]# ######################## Shortest path is 132 steps: b, a, c, d, f, e, g ################# #i.G..c...e..H.p# ########.######## #j.A..b...f..D.o# ########@######## #k.E..a...g..B.n# ########.######## #l.F..d...h..C.m# ################# Shortest paths are 136 steps; one is: a, f, b, j, g, n, h, d, l, o, e, p, c, i, k, m ######################## #@..............ac.GI.b# ###d#e#f################ ###A#B#C################ ###g#h#i################ ######################## Shortest paths are 81 steps; one is: a, c, f, i, d, g, b, e, h How many steps is the shortest path that collects all of the keys? Your puzzle answer was 4192. --- Part Two --- You arrive at the vault only to discover that there is not one vault, but four - each with its own entrance. On your map, find the area in the middle that looks like this: ... .@. ... Update your map to instead use the correct data: @#@ ### @#@ This change will split your map into four separate sections, each with its own entrance: ####### ####### #a.#Cd# #a.#Cd# ##...## ##@#@## ##.@.## --> ####### ##...## ##@#@## #cB#Ab# #cB#Ab# ####### ####### Because some of the keys are for doors in other vaults, it would take much too long to collect all of the keys by yourself. Instead, you deploy four remote-controlled robots. Each starts at one of the entrances (@). Your goal is still to collect all of the keys in the fewest steps, but now, each robot has its own position and can move independently. You can only remotely control a single robot at a time. Collecting a key instantly unlocks any corresponding doors, regardless of the vault in which the key or door is found. For example, in the map above, the top-left robot first collects key a, unlocking door A in the bottom-right vault: ####### #@.#Cd# ##.#@## ####### ##@#@## #cB#.b# ####### Then, the bottom-right robot collects key b, unlocking door B in the bottom-left vault: ####### #@.#Cd# ##.#@## ####### ##@#.## #c.#.@# ####### Then, the bottom-left robot collects key c: ####### #@.#.d# ##.#@## ####### ##.#.## #@.#.@# ####### Finally, the top-right robot collects key d: ####### #@.#.@# ##.#.## ####### ##.#.## #@.#.@# ####### In this example, it only took 8 steps to collect all of the keys. Sometimes, multiple robots might have keys available, or a robot might have to wait for multiple keys to be collected: ############### #d.ABC.#.....a# ######@#@###### ############### ######@#@###### #b.....#.....c# ############### First, the top-right, bottom-left, and bottom-right robots take turns collecting keys a, b, and c, a total of 6 + 6 + 6 = 18 steps. Then, the top-left robot can access key d, spending another 6 steps; collecting all of the keys here takes a minimum of 24 steps. Here's a more complex example: ############# #DcBa.#.GhKl# #.###@#@#I### #e#d#####j#k# ###C#@#@###J# #fEbA.#.FgHi# ############# Top-left robot collects key a. Bottom-left robot collects key b. Top-left robot collects key c. Bottom-left robot collects key d. Top-left robot collects key e. Bottom-left robot collects key f. Bottom-right robot collects key g. Top-right robot collects key h. Bottom-right robot collects key i. Top-right robot collects key j. Bottom-right robot collects key k. Top-right robot collects key l. In the above example, the fewest steps to collect all of the keys is 32. Here's an example with more choices: ############# #g#f.D#..h#l# #F###e#E###.# #dCba@#@BcIJ# ############# #nK.L@#@G...# #M###N#H###.# #o#m..#i#jk.# ############# One solution with the fewest steps is: Top-left robot collects key e. Top-right robot collects key h. Bottom-right robot collects key i. Top-left robot collects key a. Top-left robot collects key b. Top-right robot collects key c. Top-left robot collects key d. Top-left robot collects key f. Top-left robot collects key g. Bottom-right robot collects key k. Bottom-right robot collects key j. Top-right robot collects key l. Bottom-left robot collects key n. Bottom-left robot collects key m. Bottom-left robot collects key o. This example requires at least 72 steps to collect all keys. After updating your map and using the remote-controlled robots, what is the fewest steps necessary to collect all of the keys?
268
--- Day 17: No Such Thing as Too Much --- The elves bought too much eggnog again - 150 liters this time. To fit it all into your refrigerator, you'll need to move it into smaller containers. You take an inventory of the capacities of the available containers. For example, suppose you have containers of size 20, 15, 10, 5, and 5 liters. If you need to store 25 liters, there are four ways to do it: 15 and 10 20 and 5 (the first 5) 20 and 5 (the second 5) 15, 5, and 5 Filling all containers entirely, how many different combinations of containers can exactly fit all 150 liters of eggnog? Your puzzle answer was 1638. --- Part Two --- While playing with all the containers in the kitchen, another load of eggnog arrives! The shipping and receiving department is requesting as many containers as you can spare. Find the minimum number of containers that can exactly fit all 150 liters of eggnog. How many different ways can you fill that number of containers and still hold exactly 150 litres? In the example above, the minimum number of containers was two. There were three ways to use that many containers, and so the answer there would be 3.
269
--- Day 2: Corruption Checksum --- As you walk through the door, a glowing humanoid shape yells in your direction. "You there! Your state appears to be idle. Come help us repair the corruption in this spreadsheet - if we take another millisecond, we'll have to display an hourglass cursor!" The spreadsheet consists of rows of apparently-random numbers. To make sure the recovery process is on the right track, they need you to calculate the spreadsheet's checksum. For each row, determine the difference between the largest value and the smallest value; the checksum is the sum of all of these differences. For example, given the following spreadsheet: 5 1 9 5 7 5 3 2 4 6 8 The first row's largest and smallest values are 9 and 1, and their difference is 8. The second row's largest and smallest values are 7 and 3, and their difference is 4. The third row's difference is 6. In this example, the spreadsheet's checksum would be 8 + 4 + 6 = 18. What is the checksum for the spreadsheet in your puzzle input?
270
--- Day 5: A Maze of Twisty Trampolines, All Alike --- An urgent interrupt arrives from the CPU: it's trapped in a maze of jump instructions, and it would like assistance from any programs with spare cycles to help find the exit. The message includes a list of the offsets for each jump. Jumps are relative: -1 moves to the previous instruction, and 2 skips the next one. Start at the first instruction in the list. The goal is to follow the jumps until one leads outside the list. In addition, these instructions are a little strange; after each jump, the offset of that instruction increases by 1. So, if you come across an offset of 3, you would move three instructions forward, but change it to a 4 for the next time it is encountered. For example, consider the following list of jump offsets: 0 3 0 1 -3 Positive jumps ("forward") move downward; negative jumps move upward. For legibility in this example, these offset values will be written all on one line, with the current instruction marked in parentheses. The following steps would be taken before an exit is found: (0) 3 0 1 -3 - before we have taken any steps. (1) 3 0 1 -3 - jump with offset 0 (that is, don't jump at all). Fortunately, the instruction is then incremented to 1. 2 (3) 0 1 -3 - step forward because of the instruction we just modified. The first instruction is incremented again, now to 2. 2 4 0 1 (-3) - jump all the way to the end; leave a 4 behind. 2 (4) 0 1 -2 - go back to where we just were; increment -3 to -2. 2 5 0 1 -2 - jump 4 steps forward, escaping the maze. In this example, the exit is reached in 5 steps. How many steps does it take to reach the exit? Your puzzle answer was 336905. --- Part Two --- Now, the jumps are even stranger: after each jump, if the offset was three or more, instead decrease it by 1. Otherwise, increase it by 1 as before. Using this rule with the above example, the process now takes 10 steps, and the offset values after finding the exit are left as 2 3 2 3 -1. How many steps does it now take to reach the exit?
271
--- Day 21: Dirac Dice --- There's not much to do as you slowly descend to the bottom of the ocean. The submarine computer challenges you to a nice game of Dirac Dice. This game consists of a single die, two pawns, and a game board with a circular track containing ten spaces marked 1 through 10 clockwise. Each player's starting space is chosen randomly (your puzzle input). Player 1 goes first. Players take turns moving. On each player's turn, the player rolls the die three times and adds up the results. Then, the player moves their pawn that many times forward around the track (that is, moving clockwise on spaces in order of increasing value, wrapping back around to 1 after 10). So, if a player is on space 7 and they roll 2, 2, and 1, they would move forward 5 times, to spaces 8, 9, 10, 1, and finally stopping on 2. After each player moves, they increase their score by the value of the space their pawn stopped on. Players' scores start at 0. So, if the first player starts on space 7 and rolls a total of 5, they would stop on space 2 and add 2 to their score (for a total score of 2). The game immediately ends as a win for any player whose score reaches at least 1000. Since the first game is a practice game, the submarine opens a compartment labeled deterministic dice and a 100-sided die falls out. This die always rolls 1 first, then 2, then 3, and so on up to 100, after which it starts over at 1 again. Play using this die. For example, given these starting positions: Player 1 starting position: 4 Player 2 starting position: 8 This is how the game would go: Player 1 rolls 1+2+3 and moves to space 10 for a total score of 10. Player 2 rolls 4+5+6 and moves to space 3 for a total score of 3. Player 1 rolls 7+8+9 and moves to space 4 for a total score of 14. Player 2 rolls 10+11+12 and moves to space 6 for a total score of 9. Player 1 rolls 13+14+15 and moves to space 6 for a total score of 20. Player 2 rolls 16+17+18 and moves to space 7 for a total score of 16. Player 1 rolls 19+20+21 and moves to space 6 for a total score of 26. Player 2 rolls 22+23+24 and moves to space 6 for a total score of 22. ...after many turns... Player 2 rolls 82+83+84 and moves to space 6 for a total score of 742. Player 1 rolls 85+86+87 and moves to space 4 for a total score of 990. Player 2 rolls 88+89+90 and moves to space 3 for a total score of 745. Player 1 rolls 91+92+93 and moves to space 10 for a final score, 1000. Since player 1 has at least 1000 points, player 1 wins and the game ends. At this point, the losing player had 745 points and the die had been rolled a total of 993 times; 745 * 993 = 739785. Play a practice game using the deterministic 100-sided die. The moment either player wins, what do you get if you multiply the score of the losing player by the number of times the die was rolled during the game? Your puzzle answer was 1002474. --- Part Two --- Now that you're warmed up, it's time to play the real game. A second compartment opens, this time labeled Dirac dice. Out of it falls a single three-sided die. As you experiment with the die, you feel a little strange. An informational brochure in the compartment explains that this is a quantum die: when you roll it, the universe splits into multiple copies, one copy for each possible outcome of the die. In this case, rolling the die always splits the universe into three copies: one where the outcome of the roll was 1, one where it was 2, and one where it was 3. The game is played the same as before, although to prevent things from getting too far out of hand, the game now ends when either player's score reaches at least 21. Using the same starting positions as in the example above, player 1 wins in 444356092776315 universes, while player 2 merely wins in 341960390180808 universes. Using your given starting positions, determine every possible outcome. Find the player that wins in more universes; in how many universes does that player win?
272
--- Day 8: Two-Factor Authentication --- You come across a door implementing what you can only assume is an implementation of two-factor authentication after a long game of requirements telephone. To get past the door, you first swipe a keycard (no problem; there was one on a nearby desk). Then, it displays a code on a little screen, and you type that code on a keypad. Then, presumably, the door unlocks. Unfortunately, the screen has been smashed. After a few minutes, you've taken everything apart and figured out how it works. Now you just have to work out what the screen would have displayed. The magnetic strip on the card you swiped encodes a series of instructions for the screen; these instructions are your puzzle input. The screen is 50 pixels wide and 6 pixels tall, all of which start off, and is capable of three somewhat peculiar operations: rect AxB turns on all of the pixels in a rectangle at the top-left of the screen which is A wide and B tall. rotate row y=A by B shifts all of the pixels in row A (0 is the top row) right by B pixels. Pixels that would fall off the right end appear at the left end of the row. rotate column x=A by B shifts all of the pixels in column A (0 is the left column) down by B pixels. Pixels that would fall off the bottom appear at the top of the column. For example, here is a simple sequence on a smaller screen: rect 3x2 creates a small rectangle in the top-left corner: ###.... ###.... ....... rotate column x=1 by 1 rotates the second column down by one pixel: #.#.... ###.... .#..... rotate row y=0 by 4 rotates the top row right by four pixels: ....#.# ###.... .#..... rotate column x=1 by 1 again rotates the second column down by one pixel, causing the bottom pixel to wrap back to the top: .#..#.# #.#.... .#..... As you can see, this display technology is extremely powerful, and will soon dominate the tiny-code-displaying-screen market. That's what the advertisement on the back of the display tries to convince you, anyway. There seems to be an intermediate check of the voltage used by the display: after you swipe your card, if the screen did work, how many pixels should be lit? Your puzzle answer was 123. --- Part Two --- You notice that the screen is only capable of displaying capital letters; in the font it uses, each letter is 5 pixels wide and 6 tall. After you swipe your card, what code is the screen trying to display?
273
--- Day 24: Immune System Simulator 20XX --- After a weird buzzing noise, you appear back at the man's cottage. He seems relieved to see his friend, but quickly notices that the little reindeer caught some kind of cold while out exploring. The portly man explains that this reindeer's immune system isn't similar to regular reindeer immune systems: The immune system and the infection each have an army made up of several groups; each group consists of one or more identical units. The armies repeatedly fight until only one army has units remaining. Units within a group all have the same hit points (amount of damage a unit can take before it is destroyed), attack damage (the amount of damage each unit deals), an attack type, an initiative (higher initiative units attack first and win ties), and sometimes weaknesses or immunities. Here is an example group: 18 units each with 729 hit points (weak to fire; immune to cold, slashing) with an attack that does 8 radiation damage at initiative 10 Each group also has an effective power: the number of units in that group multiplied by their attack damage. The above group has an effective power of 18 * 8 = 144. Groups never have zero or negative units; instead, the group is removed from combat. Each fight consists of two phases: target selection and attacking. During the target selection phase, each group attempts to choose one target. In decreasing order of effective power, groups choose their targets; in a tie, the group with the higher initiative chooses first. The attacking group chooses to target the group in the enemy army to which it would deal the most damage (after accounting for weaknesses and immunities, but not accounting for whether the defending group has enough units to actually receive all of that damage). If an attacking group is considering two defending groups to which it would deal equal damage, it chooses to target the defending group with the largest effective power; if there is still a tie, it chooses the defending group with the highest initiative. If it cannot deal any defending groups damage, it does not choose a target. Defending groups can only be chosen as a target by one attacking group. At the end of the target selection phase, each group has selected zero or one groups to attack, and each group is being attacked by zero or one groups. During the attacking phase, each group deals damage to the target it selected, if any. Groups attack in decreasing order of initiative, regardless of whether they are part of the infection or the immune system. (If a group contains no units, it cannot attack.) The damage an attacking group deals to a defending group depends on the attacking group's attack type and the defending group's immunities and weaknesses. By default, an attacking group would deal damage equal to its effective power to the defending group. However, if the defending group is immune to the attacking group's attack type, the defending group instead takes no damage; if the defending group is weak to the attacking group's attack type, the defending group instead takes double damage. The defending group only loses whole units from damage; damage is always dealt in such a way that it kills the most units possible, and any remaining damage to a unit that does not immediately kill it is ignored. For example, if a defending group contains 10 units with 10 hit points each and receives 75 damage, it loses exactly 7 units and is left with 3 units at full health. After the fight is over, if both armies still contain units, a new fight begins; combat only ends once one army has lost all of its units. For example, consider the following armies: Immune System: 17 units each with 5390 hit points (weak to radiation, bludgeoning) with an attack that does 4507 fire damage at initiative 2 989 units each with 1274 hit points (immune to fire; weak to bludgeoning, slashing) with an attack that does 25 slashing damage at initiative 3 Infection: 801 units each with 4706 hit points (weak to radiation) with an attack that does 116 bludgeoning damage at initiative 1 4485 units each with 2961 hit points (immune to radiation; weak to fire, cold) with an attack that does 12 slashing damage at initiative 4 If these armies were to enter combat, the following fights, including details during the target selection and attacking phases, would take place: Immune System: Group 1 contains 17 units Group 2 contains 989 units Infection: Group 1 contains 801 units Group 2 contains 4485 units Infection group 1 would deal defending group 1 185832 damage Infection group 1 would deal defending group 2 185832 damage Infection group 2 would deal defending group 2 107640 damage Immune System group 1 would deal defending group 1 76619 damage Immune System group 1 would deal defending group 2 153238 damage Immune System group 2 would deal defending group 1 24725 damage Infection group 2 attacks defending group 2, killing 84 units Immune System group 2 attacks defending group 1, killing 4 units Immune System group 1 attacks defending group 2, killing 51 units Infection group 1 attacks defending group 1, killing 17 units Immune System: Group 2 contains 905 units Infection: Group 1 contains 797 units Group 2 contains 4434 units Infection group 1 would deal defending group 2 184904 damage Immune System group 2 would deal defending group 1 22625 damage Immune System group 2 would deal defending group 2 22625 damage Immune System group 2 attacks defending group 1, killing 4 units Infection group 1 attacks defending group 2, killing 144 units Immune System: Group 2 contains 761 units Infection: Group 1 contains 793 units Group 2 contains 4434 units Infection group 1 would deal defending group 2 183976 damage Immune System group 2 would deal defending group 1 19025 damage Immune System group 2 would deal defending group 2 19025 damage Immune System group 2 attacks defending group 1, killing 4 units Infection group 1 attacks defending group 2, killing 143 units Immune System: Group 2 contains 618 units Infection: Group 1 contains 789 units Group 2 contains 4434 units Infection group 1 would deal defending group 2 183048 damage Immune System group 2 would deal defending group 1 15450 damage Immune System group 2 would deal defending group 2 15450 damage Immune System group 2 attacks defending group 1, killing 3 units Infection group 1 attacks defending group 2, killing 143 units Immune System: Group 2 contains 475 units Infection: Group 1 contains 786 units Group 2 contains 4434 units Infection group 1 would deal defending group 2 182352 damage Immune System group 2 would deal defending group 1 11875 damage Immune System group 2 would deal defending group 2 11875 damage Immune System group 2 attacks defending group 1, killing 2 units Infection group 1 attacks defending group 2, killing 142 units Immune System: Group 2 contains 333 units Infection: Group 1 contains 784 units Group 2 contains 4434 units Infection group 1 would deal defending group 2 181888 damage Immune System group 2 would deal defending group 1 8325 damage Immune System group 2 would deal defending group 2 8325 damage Immune System group 2 attacks defending group 1, killing 1 unit Infection group 1 attacks defending group 2, killing 142 units Immune System: Group 2 contains 191 units Infection: Group 1 contains 783 units Group 2 contains 4434 units Infection group 1 would deal defending group 2 181656 damage Immune System group 2 would deal defending group 1 4775 damage Immune System group 2 would deal defending group 2 4775 damage Immune System group 2 attacks defending group 1, killing 1 unit Infection group 1 attacks defending group 2, killing 142 units Immune System: Group 2 contains 49 units Infection: Group 1 contains 782 units Group 2 contains 4434 units Infection group 1 would deal defending group 2 181424 damage Immune System group 2 would deal defending group 1 1225 damage Immune System group 2 would deal defending group 2 1225 damage Immune System group 2 attacks defending group 1, killing 0 units Infection group 1 attacks defending group 2, killing 49 units Immune System: No groups remain. Infection: Group 1 contains 782 units Group 2 contains 4434 units In the example above, the winning army ends up with 782 + 4434 = 5216 units. You scan the reindeer's condition (your puzzle input); the white-bearded man looks nervous. As it stands now, how many units would the winning army have?
274
--- Day 15: Rambunctious Recitation --- You catch the airport shuttle and try to book a new flight to your vacation island. Due to the storm, all direct flights have been cancelled, but a route is available to get around the storm. You take it. While you wait for your flight, you decide to check in with the Elves back at the North Pole. They're playing a memory game and are ever so excited to explain the rules! In this game, the players take turns saying numbers. They begin by taking turns reading from a list of starting numbers (your puzzle input). Then, each turn consists of considering the most recently spoken number: If that was the first time the number has been spoken, the current player says 0. Otherwise, the number had been spoken before; the current player announces how many turns apart the number is from when it was previously spoken. So, after the starting numbers, each turn results in that player speaking aloud either 0 (if the last number is new) or an age (if the last number is a repeat). For example, suppose the starting numbers are 0,3,6: Turn 1: The 1st number spoken is a starting number, 0. Turn 2: The 2nd number spoken is a starting number, 3. Turn 3: The 3rd number spoken is a starting number, 6. Turn 4: Now, consider the last number spoken, 6. Since that was the first time the number had been spoken, the 4th number spoken is 0. Turn 5: Next, again consider the last number spoken, 0. Since it had been spoken before, the next number to speak is the difference between the turn number when it was last spoken (the previous turn, 4) and the turn number of the time it was most recently spoken before then (turn 1). Thus, the 5th number spoken is 4 - 1, 3. Turn 6: The last number spoken, 3 had also been spoken before, most recently on turns 5 and 2. So, the 6th number spoken is 5 - 2, 3. Turn 7: Since 3 was just spoken twice in a row, and the last two turns are 1 turn apart, the 7th number spoken is 1. Turn 8: Since 1 is new, the 8th number spoken is 0. Turn 9: 0 was last spoken on turns 8 and 4, so the 9th number spoken is the difference between them, 4. Turn 10: 4 is new, so the 10th number spoken is 0. (The game ends when the Elves get sick of playing or dinner is ready, whichever comes first.) Their question for you is: what will be the 2020th number spoken? In the example above, the 2020th number spoken will be 436. Here are a few more examples: Given the starting numbers 1,3,2, the 2020th number spoken is 1. Given the starting numbers 2,1,3, the 2020th number spoken is 10. Given the starting numbers 1,2,3, the 2020th number spoken is 27. Given the starting numbers 2,3,1, the 2020th number spoken is 78. Given the starting numbers 3,2,1, the 2020th number spoken is 438. Given the starting numbers 3,1,2, the 2020th number spoken is 1836. Given your starting numbers, what will be the 2020th number spoken?
275
--- Day 3: Perfectly Spherical Houses in a Vacuum --- Santa is delivering presents to an infinite two-dimensional grid of houses. He begins by delivering a present to the house at his starting location, and then an elf at the North Pole calls him via radio and tells him where to move next. Moves are always exactly one house to the north (^), south (v), east (>), or west (<). After each move, he delivers another present to the house at his new location. However, the elf back at the north pole has had a little too much eggnog, and so his directions are a little off, and Santa ends up visiting some houses more than once. How many houses receive at least one present? For example: > delivers presents to 2 houses: one at the starting location, and one to the east. ^>v< delivers presents to 4 houses in a square, including twice to the house at his starting/ending location. ^v^v^v^v^v delivers a bunch of presents to some very lucky children at only 2 houses.
276
--- Day 21: Fractal Art --- You find a program trying to generate some art. It uses a strange process that involves repeatedly enhancing the detail of an image through a set of rules. The image consists of a two-dimensional square grid of pixels that are either on (#) or off (.). The program always begins with this pattern: .#. ..# ### Because the pattern is both 3 pixels wide and 3 pixels tall, it is said to have a size of 3. Then, the program repeats the following process: If the size is evenly divisible by 2, break the pixels up into 2x2 squares, and convert each 2x2 square into a 3x3 square by following the corresponding enhancement rule. Otherwise, the size is evenly divisible by 3; break the pixels up into 3x3 squares, and convert each 3x3 square into a 4x4 square by following the corresponding enhancement rule. Because each square of pixels is replaced by a larger one, the image gains pixels and so its size increases. The artist's book of enhancement rules is nearby (your puzzle input); however, it seems to be missing rules. The artist explains that sometimes, one must rotate or flip the input pattern to find a match. (Never rotate or flip the output pattern, though.) Each pattern is written concisely: rows are listed as single units, ordered top-down, and separated by slashes. For example, the following rules correspond to the adjacent patterns: ../.# = .. .# .#. .#./..#/### = ..# ### #..# #..#/..../#..#/.##. = .... #..# .##. When searching for a rule to use, rotate and flip the pattern as necessary. For example, all of the following patterns match the same rule: .#. .#. #.. ### ..# #.. #.# ..# ### ### ##. .#. Suppose the book contained the following two rules: ../.# => ##./#../... .#./..#/### => #..#/..../..../#..# As before, the program begins with this pattern: .#. ..# ### The size of the grid (3) is not divisible by 2, but it is divisible by 3. It divides evenly into a single square; the square matches the second rule, which produces: #..# .... .... #..# The size of this enhanced grid (4) is evenly divisible by 2, so that rule is used. It divides evenly into four squares: #.|.# ..|.. --+-- ..|.. #.|.# Each of these squares matches the same rule (../.# => ##./#../...), three of which require some flipping and rotation to line up with the rule. The output for the rule is the same in all four cases: ##.|##. #..|#.. ...|... ---+--- ##.|##. #..|#.. ...|... Finally, the squares are joined into a new grid: ##.##. #..#.. ...... ##.##. #..#.. ...... Thus, after 2 iterations, the grid contains 12 pixels that are on. How many pixels stay on after 5 iterations? Your puzzle answer was 117. --- Part Two --- How many pixels stay on after 18 iterations?
277
--- Day 9: Explosives in Cyberspace --- Wandering around a secure area, you come across a datalink port to a new part of the network. After briefly scanning it for interesting files, you find one file in particular that catches your attention. It's compressed with an experimental format, but fortunately, the documentation for the format is nearby. The format compresses a sequence of characters. Whitespace is ignored. To indicate that some sequence should be repeated, a marker is added to the file, like (10x2). To decompress this marker, take the subsequent 10 characters and repeat them 2 times. Then, continue reading the file after the repeated data. The marker itself is not included in the decompressed output. If parentheses or other characters appear within the data referenced by a marker, that's okay - treat it like normal data, not a marker, and then resume looking for markers after the decompressed section. For example: ADVENT contains no markers and decompresses to itself with no changes, resulting in a decompressed length of 6. A(1x5)BC repeats only the B a total of 5 times, becoming ABBBBBC for a decompressed length of 7. (3x3)XYZ becomes XYZXYZXYZ for a decompressed length of 9. A(2x2)BCD(2x2)EFG doubles the BC and EF, becoming ABCBCDEFEFG for a decompressed length of 11. (6x1)(1x3)A simply becomes (1x3)A - the (1x3) looks like a marker, but because it's within a data section of another marker, it is not treated any differently from the A that comes after it. It has a decompressed length of 6. X(8x2)(3x3)ABCY becomes X(3x3)ABC(3x3)ABCY (for a decompressed length of 18), because the decompressed data from the (8x2) marker (the (3x3)ABC) is skipped and not processed further. What is the decompressed length of the file (your puzzle input)? Don't count whitespace.
278
--- Day 15: Beverage Bandits --- Having perfected their hot chocolate, the Elves have a new problem: the Goblins that live in these caves will do anything to steal it. Looks like they're here for a fight. You scan the area, generating a map of the walls (#), open cavern (.), and starting position of every Goblin (G) and Elf (E) (your puzzle input). Combat proceeds in rounds; in each round, each unit that is still alive takes a turn, resolving all of its actions before the next unit's turn begins. On each unit's turn, it tries to move into range of an enemy (if it isn't already) and then attack (if it is in range). All units are very disciplined and always follow very strict combat rules. Units never move or attack diagonally, as doing so would be dishonorable. When multiple choices are equally valid, ties are broken in reading order: top-to-bottom, then left-to-right. For instance, the order in which units take their turns within a round is the reading order of their starting positions in that round, regardless of the type of unit or whether other units have moved after the round started. For example: would take their These units: turns in this order: ####### ####### #.G.E.# #.1.2.# #E.G.E# #3.4.5# #.G.E.# #.6.7.# ####### ####### Each unit begins its turn by identifying all possible targets (enemy units). If no targets remain, combat ends. Then, the unit identifies all of the open squares (.) that are in range of each target; these are the squares which are adjacent (immediately up, down, left, or right) to any target and which aren't already occupied by a wall or another unit. Alternatively, the unit might already be in range of a target. If the unit is not already in range of a target, and there are no open squares which are in range of a target, the unit ends its turn. If the unit is already in range of a target, it does not move, but continues its turn with an attack. Otherwise, since it is not in range of a target, it moves. To move, the unit first considers the squares that are in range and determines which of those squares it could reach in the fewest steps. A step is a single movement to any adjacent (immediately up, down, left, or right) open (.) square. Units cannot move into walls or other units. The unit does this while considering the current positions of units and does not do any prediction about where units will be later. If the unit cannot reach (find an open path to) any of the squares that are in range, it ends its turn. If multiple squares are in range and tied for being reachable in the fewest steps, the square which is first in reading order is chosen. For example: Targets: In range: Reachable: Nearest: Chosen: ####### ####### ####### ####### ####### #E..G.# #E.?G?# #E.@G.# #E.!G.# #E.+G.# #...#.# --> #.?.#?# --> #.@.#.# --> #.!.#.# --> #...#.# #.G.#G# #?G?#G# #@G@#G# #!G.#G# #.G.#G# ####### ####### ####### ####### ####### In the above scenario, the Elf has three targets (the three Goblins): Each of the Goblins has open, adjacent squares which are in range (marked with a ? on the map). Of those squares, four are reachable (marked @); the other two (on the right) would require moving through a wall or unit to reach. Three of these reachable squares are nearest, requiring the fewest steps (only 2) to reach (marked !). Of those, the square which is first in reading order is chosen (+). The unit then takes a single step toward the chosen square along the shortest path to that square. If multiple steps would put the unit equally closer to its destination, the unit chooses the step which is first in reading order. (This requires knowing when there is more than one shortest path so that you can consider the first step of each such path.) For example: In range: Nearest: Chosen: Distance: Step: ####### ####### ####### ####### ####### #.E...# #.E...# #.E...# #4E212# #..E..# #...?.# --> #...!.# --> #...+.# --> #32101# --> #.....# #..?G?# #..!G.# #...G.# #432G2# #...G.# ####### ####### ####### ####### ####### The Elf sees three squares in range of a target (?), two of which are nearest (!), and so the first in reading order is chosen (+). Under "Distance", each open square is marked with its distance from the destination square; the two squares to which the Elf could move on this turn (down and to the right) are both equally good moves and would leave the Elf 2 steps from being in range of the Goblin. Because the step which is first in reading order is chosen, the Elf moves right one square. Here's a larger example of movement: Initially: ######### #G..G..G# #.......# #.......# #G..E..G# #.......# #.......# #G..G..G# ######### After 1 round: ######### #.G...G.# #...G...# #...E..G# #.G.....# #.......# #G..G..G# #.......# ######### After 2 rounds: ######### #..G.G..# #...G...# #.G.E.G.# #.......# #G..G..G# #.......# #.......# ######### After 3 rounds: ######### #.......# #..GGG..# #..GEG..# #G..G...# #......G# #.......# #.......# ######### Once the Goblins and Elf reach the positions above, they all are either in range of a target or cannot find any square in range of a target, and so none of the units can move until a unit dies. After moving (or if the unit began its turn in range of a target), the unit attacks. To attack, the unit first determines all of the targets that are in range of it by being immediately adjacent to it. If there are no such targets, the unit ends its turn. Otherwise, the adjacent target with the fewest hit points is selected; in a tie, the adjacent target with the fewest hit points which is first in reading order is selected. The unit deals damage equal to its attack power to the selected target, reducing its hit points by that amount. If this reduces its hit points to 0 or fewer, the selected target dies: its square becomes . and it takes no further turns. Each unit, either Goblin or Elf, has 3 attack power and starts with 200 hit points. For example, suppose the only Elf is about to attack: HP: HP: G.... 9 G.... 9 ..G.. 4 ..G.. 4 ..EG. 2 --> ..E.. ..G.. 2 ..G.. 2 ...G. 1 ...G. 1 The "HP" column shows the hit points of the Goblin to the left in the corresponding row. The Elf is in range of three targets: the Goblin above it (with 4 hit points), the Goblin to its right (with 2 hit points), and the Goblin below it (also with 2 hit points). Because three targets are in range, the ones with the lowest hit points are selected: the two Goblins with 2 hit points each (one to the right of the Elf and one below the Elf). Of those, the Goblin first in reading order (the one to the right of the Elf) is selected. The selected Goblin's hit points (2) are reduced by the Elf's attack power (3), reducing its hit points to -1, killing it. After attacking, the unit's turn ends. Regardless of how the unit's turn ends, the next unit in the round takes its turn. If all units have taken turns in this round, the round ends, and a new round begins. The Elves look quite outnumbered. You need to determine the outcome of the battle: the number of full rounds that were completed (not counting the round in which combat ends) multiplied by the sum of the hit points of all remaining units at the moment combat ends. (Combat only ends when a unit finds no targets during its turn.) Below is an entire sample combat. Next to each map, each row's units' hit points are listed from left to right. Initially: ####### #.G...# G(200) #...EG# E(200), G(200) #.#.#G# G(200) #..G#E# G(200), E(200) #.....# ####### After 1 round: ####### #..G..# G(200) #...EG# E(197), G(197) #.#G#G# G(200), G(197) #...#E# E(197) #.....# ####### After 2 rounds: ####### #...G.# G(200) #..GEG# G(200), E(188), G(194) #.#.#G# G(194) #...#E# E(194) #.....# ####### Combat ensues; eventually, the top Elf dies: After 23 rounds: ####### #...G.# G(200) #..G.G# G(200), G(131) #.#.#G# G(131) #...#E# E(131) #.....# ####### After 24 rounds: ####### #..G..# G(200) #...G.# G(131) #.#G#G# G(200), G(128) #...#E# E(128) #.....# ####### After 25 rounds: ####### #.G...# G(200) #..G..# G(131) #.#.#G# G(125) #..G#E# G(200), E(125) #.....# ####### After 26 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(122) #...#E# E(122) #..G..# G(200) ####### After 27 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(119) #...#E# E(119) #...G.# G(200) ####### After 28 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(116) #...#E# E(113) #....G# G(200) ####### More combat ensues; eventually, the bottom Elf dies: After 47 rounds: ####### #G....# G(200) #.G...# G(131) #.#.#G# G(59) #...#.# #....G# G(200) ####### Before the 48th round can finish, the top-left Goblin finds that there are no targets remaining, and so combat ends. So, the number of full rounds that were completed is 47, and the sum of the hit points of all remaining units is 200+131+59+200 = 590. From these, the outcome of the battle is 47 * 590 = 27730. Here are a few example summarized combats: ####### ####### #G..#E# #...#E# E(200) #E#E.E# #E#...# E(197) #G.##.# --> #.E##.# E(185) #...#E# #E..#E# E(200), E(200) #...E.# #.....# ####### ####### Combat ends after 37 full rounds Elves win with 982 total hit points left Outcome: 37 * 982 = 36334 ####### ####### #E..EG# #.E.E.# E(164), E(197) #.#G.E# #.#E..# E(200) #E.##E# --> #E.##.# E(98) #G..#.# #.E.#.# E(200) #..E#.# #...#.# ####### ####### Combat ends after 46 full rounds Elves win with 859 total hit points left Outcome: 46 * 859 = 39514 ####### ####### #E.G#.# #G.G#.# G(200), G(98) #.#G..# #.#G..# G(200) #G.#.G# --> #..#..# #G..#.# #...#G# G(95) #...E.# #...G.# G(200) ####### ####### Combat ends after 35 full rounds Goblins win with 793 total hit points left Outcome: 35 * 793 = 27755 ####### ####### #.E...# #.....# #.#..G# #.#G..# G(200) #.###.# --> #.###.# #E#G#G# #.#.#.# #...#G# #G.G#G# G(98), G(38), G(200) ####### ####### Combat ends after 54 full rounds Goblins win with 536 total hit points left Outcome: 54 * 536 = 28944 ######### ######### #G......# #.G.....# G(137) #.E.#...# #G.G#...# G(200), G(200) #..##..G# #.G##...# G(200) #...##..# --> #...##..# #...#...# #.G.#...# G(200) #.G...G.# #.......# #.....G.# #.......# ######### ######### Combat ends after 20 full rounds Goblins win with 937 total hit points left Outcome: 20 * 937 = 18740 What is the outcome of the combat described in your puzzle input?
279
--- Day 5: Doesn't He Have Intern-Elves For This? --- Santa needs help figuring out which strings in his text file are naughty or nice. A nice string is one with all of the following properties: It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou. It contains at least one letter that appears twice in a row, like xx, abcdde (dd), or aabbccdd (aa, bb, cc, or dd). It does not contain the strings ab, cd, pq, or xy, even if they are part of one of the other requirements. For example: ugknbfddgicrmopn is nice because it has at least three vowels (u...i...o...), a double letter (...dd...), and none of the disallowed substrings. aaa is nice because it has at least three vowels and a double letter, even though the letters used by different rules overlap. jchzalrnumimnmhp is naughty because it has no double letter. haegwjzuvuyypxyu is naughty because it contains the string xy. dvszwmarrgswjxmb is naughty because it contains only one vowel. How many strings are nice? Your puzzle answer was 255. --- Part Two --- Realizing the error of his ways, Santa has switched to a better model of determining whether a string is naughty or nice. None of the old rules apply, as they are all clearly ridiculous. Now, a nice string is one with all of the following properties: It contains a pair of any two letters that appears at least twice in the string without overlapping, like xyxy (xy) or aabcdefgaa (aa), but not like aaa (aa, but it overlaps). It contains at least one letter which repeats with exactly one letter between them, like xyx, abcdefeghi (efe), or even aaa. For example: qjhvhtzxzqqjkmpb is nice because is has a pair that appears twice (qj) and a letter that repeats with exactly one letter between them (zxz). xxyxx is nice because it has a pair that appears twice and a letter that repeats with one between, even though the letters used by each rule overlap. uurcxstgmygtbstg is naughty because it has a pair (tg) but no repeat with a single letter between them. ieodomkazucvgmuy is naughty because it has a repeating letter with one between (odo), but no pair that appears twice. How many strings are nice under these new rules?
280
--- Day 12: Rain Risk --- Your ferry made decent progress toward the island, but the storm came in faster than anyone expected. The ferry needs to take evasive actions! Unfortunately, the ship's navigation computer seems to be malfunctioning; rather than giving a route directly to safety, it produced extremely circuitous instructions. When the captain uses the PA system to ask if anyone can help, you quickly volunteer. The navigation instructions (your puzzle input) consists of a sequence of single-character actions paired with integer input values. After staring at them for a few minutes, you work out what they probably mean: Action N means to move north by the given value. Action S means to move south by the given value. Action E means to move east by the given value. Action W means to move west by the given value. Action L means to turn left the given number of degrees. Action R means to turn right the given number of degrees. Action F means to move forward by the given value in the direction the ship is currently facing. The ship starts by facing east. Only the L and R actions change the direction the ship is facing. (That is, if the ship is facing east and the next instruction is N10, the ship would move north 10 units, but would still move east if the following action were F.) For example: F10 N3 F7 R90 F11 These instructions would be handled as follows: F10 would move the ship 10 units east (because the ship starts by facing east) to east 10, north 0. N3 would move the ship 3 units north to east 10, north 3. F7 would move the ship another 7 units east (because the ship is still facing east) to east 17, north 3. R90 would cause the ship to turn right by 90 degrees and face south; it remains at east 17, north 3. F11 would move the ship 11 units south to east 17, south 8. At the end of these instructions, the ship's Manhattan distance (sum of the absolute values of its east/west position and its north/south position) from its starting position is 17 + 8 = 25. Figure out where the navigation instructions lead. What is the Manhattan distance between that location and the ship's starting position?
281
--- Day 24: Electromagnetic Moat --- The CPU itself is a large, black building surrounded by a bottomless pit. Enormous metal tubes extend outward from the side of the building at regular intervals and descend down into the void. There's no way to cross, but you need to get inside. No way, of course, other than building a bridge out of the magnetic components strewn about nearby. Each component has two ports, one on each end. The ports come in all different types, and only matching types can be connected. You take an inventory of the components by their port types (your puzzle input). Each port is identified by the number of pins it uses; more pins mean a stronger connection for your bridge. A 3/7 component, for example, has a type-3 port on one side, and a type-7 port on the other. Your side of the pit is metallic; a perfect surface to connect a magnetic, zero-pin port. Because of this, the first port you use must be of type 0. It doesn't matter what type of port you end with; your goal is just to make the bridge as strong as possible. The strength of a bridge is the sum of the port types in each component. For example, if your bridge is made of components 0/3, 3/7, and 7/4, your bridge has a strength of 0+3 + 3+7 + 7+4 = 24. For example, suppose you had the following components: 0/2 2/2 2/3 3/4 3/5 0/1 10/1 9/10 With them, you could make the following valid bridges: 0/1 0/1--10/1 0/1--10/1--9/10 0/2 0/2--2/3 0/2--2/3--3/4 0/2--2/3--3/5 0/2--2/2 0/2--2/2--2/3 0/2--2/2--2/3--3/4 0/2--2/2--2/3--3/5 (Note how, as shown by 10/1, order of ports within a component doesn't matter. However, you may only use each port on a component once.) Of these bridges, the strongest one is 0/1--10/1--9/10; it has a strength of 0+1 + 1+10 + 10+9 = 31. What is the strength of the strongest bridge you can make with the components you have available?
282
--- Day 12: Subterranean Sustainability --- The year 518 is significantly more underground than your history books implied. Either that, or you've arrived in a vast cavern network under the North Pole. After exploring a little, you discover a long tunnel that contains a row of small pots as far as you can see to your left and right. A few of them contain plants - someone is trying to grow things in these geothermally-heated caves. The pots are numbered, with 0 in front of you. To the left, the pots are numbered -1, -2, -3, and so on; to the right, 1, 2, 3.... Your puzzle input contains a list of pots from 0 to the right and whether they do (#) or do not (.) currently contain a plant, the initial state. (No other pots currently contain plants.) For example, an initial state of #..##.... indicates that pots 0, 3, and 4 currently contain plants. Your puzzle input also contains some notes you find on a nearby table: someone has been trying to figure out how these plants spread to nearby pots. Based on the notes, for each generation of plants, a given pot has or does not have a plant based on whether that pot (and the two pots on either side of it) had a plant in the last generation. These are written as LLCRR => N, where L are pots to the left, C is the current pot being considered, R are the pots to the right, and N is whether the current pot will have a plant in the next generation. For example: A note like ..#.. => . means that a pot that contains a plant but with no plants within two pots of it will not have a plant in it during the next generation. A note like ##.## => . means that an empty pot with two plants on each side of it will remain empty in the next generation. A note like .##.# => # means that a pot has a plant in a given generation if, in the previous generation, there were plants in that pot, the one immediately to the left, and the one two pots to the right, but not in the ones immediately to the right and two to the left. It's not clear what these plants are for, but you're sure it's important, so you'd like to make sure the current configuration of plants is sustainable by determining what will happen after 20 generations. For example, given the following input: initial state: #..#.#..##......###...### ...## => # ..#.. => # .#... => # .#.#. => # .#.## => # .##.. => # .#### => # #.#.# => # #.### => # ##.#. => # ##.## => # ###.. => # ###.# => # ####. => # For brevity, in this example, only the combinations which do produce a plant are listed. (Your input includes all possible combinations.) Then, the next 20 generations will look like this: 1 2 3 0 0 0 0 0: ...#..#.#..##......###...###........... 1: ...#...#....#.....#..#..#..#........... 2: ...##..##...##....#..#..#..##.......... 3: ..#.#...#..#.#....#..#..#...#.......... 4: ...#.#..#...#.#...#..#..##..##......... 5: ....#...##...#.#..#..#...#...#......... 6: ....##.#.#....#...#..##..##..##........ 7: ...#..###.#...##..#...#...#...#........ 8: ...#....##.#.#.#..##..##..##..##....... 9: ...##..#..#####....#...#...#...#....... 10: ..#.#..#...#.##....##..##..##..##...... 11: ...#...##...#.#...#.#...#...#...#...... 12: ...##.#.#....#.#...#.#..##..##..##..... 13: ..#..###.#....#.#...#....#...#...#..... 14: ..#....##.#....#.#..##...##..##..##.... 15: ..##..#..#.#....#....#..#.#...#...#.... 16: .#.#..#...#.#...##...#...#.#..##..##... 17: ..#...##...#.#.#.#...##...#....#...#... 18: ..##.#.#....#####.#.#.#...##...##..##.. 19: .#..###.#..#.#.#######.#.#.#..#.#...#.. 20: .#....##....#####...#######....#.#..##. The generation is shown along the left, where 0 is the initial state. The pot numbers are shown along the top, where 0 labels the center pot, negative-numbered pots extend to the left, and positive pots extend toward the right. Remember, the initial state begins at pot 0, which is not the leftmost pot used in this example. After one generation, only seven plants remain. The one in pot 0 matched the rule looking for ..#.., the one in pot 4 matched the rule looking for .#.#., pot 9 matched .##.., and so on. In this example, after 20 generations, the pots shown as # contain plants, the furthest left of which is pot -2, and the furthest right of which is pot 34. Adding up all the numbers of plant-containing pots after the 20th generation produces 325. After 20 generations, what is the sum of the numbers of all pots which contain a plant? Your puzzle answer was 3405. --- Part Two --- You realize that 20 generations aren't enough. After all, these plants will need to last another 1500 years to even reach your timeline, not to mention your future. After fifty billion (50000000000) generations, what is the sum of the numbers of all pots which contain a plant?
283
--- Day 13: Claw Contraption --- Next up: the lobby of a resort on a tropical island. The Historians take a moment to admire the hexagonal floor tiles before spreading out. Fortunately, it looks like the resort has a new arcade! Maybe you can win some prizes from the claw machines? The claw machines here are a little unusual. Instead of a joystick or directional buttons to control the claw, these machines have two buttons labeled A and B. Worse, you can't just put in a token and play; it costs 3 tokens to push the A button and 1 token to push the B button. With a little experimentation, you figure out that each machine's buttons are configured to move the claw a specific amount to the right (along the X axis) and a specific amount forward (along the Y axis) each time that button is pressed. Each machine contains one prize; to win the prize, the claw must be positioned exactly above the prize on both the X and Y axes. You wonder: what is the smallest number of tokens you would have to spend to win as many prizes as possible? You assemble a list of every machine's button behavior and prize location (your puzzle input). For example: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=8400, Y=5400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=12748, Y=12176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=7870, Y=6450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=18641, Y=10279 This list describes the button configuration and prize location of four different claw machines. For now, consider just the first claw machine in the list: Pushing the machine's A button would move the claw 94 units along the X axis and 34 units along the Y axis. Pushing the B button would move the claw 22 units along the X axis and 67 units along the Y axis. The prize is located at X=8400, Y=5400; this means that from the claw's initial position, it would need to move exactly 8400 units along the X axis and exactly 5400 units along the Y axis to be perfectly aligned with the prize in this machine. The cheapest way to win the prize is by pushing the A button 80 times and the B button 40 times. This would line up the claw along the X axis (because 80*94 + 40*22 = 8400) and along the Y axis (because 80*34 + 40*67 = 5400). Doing this would cost 80*3 tokens for the A presses and 40*1 for the B presses, a total of 280 tokens. For the second and fourth claw machines, there is no combination of A and B presses that will ever win a prize. For the third claw machine, the cheapest way to win the prize is by pushing the A button 38 times and the B button 86 times. Doing this would cost a total of 200 tokens. So, the most prizes you could possibly win is two; the minimum tokens you would have to spend to win all (two) prizes is 480. You estimate that each button would need to be pressed no more than 100 times to win a prize. How else would someone be expected to play? Figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes? Your puzzle answer was 33209. The first half of this puzzle is complete! It provides one gold star: * --- Part Two --- As you go to win the first prize, you discover that the claw is nowhere near where you expected it would be. Due to a unit conversion error in your measurements, the position of every prize is actually 10000000000000 higher on both the X and Y axis! Add 10000000000000 to the X and Y position of every prize. After making this change, the example above would now look like this: Button A: X+94, Y+34 Button B: X+22, Y+67 Prize: X=10000000008400, Y=10000000005400 Button A: X+26, Y+66 Button B: X+67, Y+21 Prize: X=10000000012748, Y=10000000012176 Button A: X+17, Y+86 Button B: X+84, Y+37 Prize: X=10000000007870, Y=10000000006450 Button A: X+69, Y+23 Button B: X+27, Y+71 Prize: X=10000000018641, Y=10000000010279 Now, it is only possible to win a prize on the second and fourth claw machines. Unfortunately, it will take many more than 100 presses to do so. Using the corrected prize coordinates, figure out how to win as many prizes as possible. What is the fewest tokens you would have to spend to win all possible prizes?
284
--- Day 22: Sporifica Virus --- Diagnostics indicate that the local grid computing cluster has been contaminated with the Sporifica Virus. The grid computing cluster is a seemingly-infinite two-dimensional grid of compute nodes. Each node is either clean or infected by the virus. To prevent overloading the nodes (which would render them useless to the virus) or detection by system administrators, exactly one virus carrier moves through the network, infecting or cleaning nodes as it moves. The virus carrier is always located on a single node in the network (the current node) and keeps track of the direction it is facing. To avoid detection, the virus carrier works in bursts; in each burst, it wakes up, does some work, and goes back to sleep. The following steps are all executed in order one time each burst: If the current node is infected, it turns to its right. Otherwise, it turns to its left. (Turning is done in-place; the current node does not change.) If the current node is clean, it becomes infected. Otherwise, it becomes cleaned. (This is done after the node is considered for the purposes of changing direction.) The virus carrier moves forward one node in the direction it is facing. Diagnostics have also provided a map of the node infection status (your puzzle input). Clean nodes are shown as .; infected nodes are shown as #. This map only shows the center of the grid; there are many more nodes beyond those shown, but none of them are currently infected. The virus carrier begins in the middle of the map facing up. For example, suppose you are given a map like this: ..# #.. ... Then, the middle of the infinite grid looks like this, with the virus carrier's position marked with [ ]: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . . #[.]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The virus carrier is on a clean node, so it turns left, infects the node, and moves left: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . .[#]# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The virus carrier is on an infected node, so it turns right, cleans the node, and moves up: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .[.]. # . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Four times in a row, the virus carrier finds a clean, infects it, turns left, and moves forward, ending in the same place and still facing up: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #[#]. # . . . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Now on the same node as before, it sees an infection, which causes it to turn right, clean the node, and move forward: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # .[.]# . . . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . After the above actions, a total of 7 bursts of activity had taken place. Of them, 5 bursts of activity caused an infection. After a total of 70, the grid looks like this, with the virus carrier facing up: . . . . . # # . . . . . . # . . # . . . . # . . . . # . . # . #[.]. . # . . # . # . . # . . . . . . # # . . . . . . . . . . . . . . . . . . . . By this time, 41 bursts of activity caused an infection (though most of those nodes have since been cleaned). After a total of 10000 bursts of activity, 5587 bursts will have caused an infection. Given your actual map, after 10000 bursts of activity, how many bursts cause a node to become infected? (Do not count nodes that begin infected.) Your puzzle answer was 5330. --- Part Two --- As you go to remove the virus from the infected nodes, it evolves to resist your attempt. Now, before it infects a clean node, it will weaken it to disable your defenses. If it encounters an infected node, it will instead flag the node to be cleaned in the future. So: Clean nodes become weakened. Weakened nodes become infected. Infected nodes become flagged. Flagged nodes become clean. Every node is always in exactly one of the above states. The virus carrier still functions in a similar way, but now uses the following logic during its bursts of action: Decide which way to turn based on the current node: If it is clean, it turns left. If it is weakened, it does not turn, and will continue moving in the same direction. If it is infected, it turns right. If it is flagged, it reverses direction, and will go back the way it came. Modify the state of the current node, as described above. The virus carrier moves forward one node in the direction it is facing. Start with the same map (still using . for clean and # for infected) and still with the virus carrier starting in the middle and facing up. Using the same initial state as the previous example, and drawing weakened as W and flagged as F, the middle of the infinite grid looks like this, with the virus carrier's position again marked with [ ]: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . . #[.]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This is the same as before, since no initial nodes are weakened or flagged. The virus carrier is on a clean node, so it still turns left, instead weakens the node, and moves left: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . . .[#]W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The virus carrier is on an infected node, so it still turns right, instead flags the node, and moves up: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .[.]. # . . . . . . F W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . This process repeats three more times, ending on the previously-flagged node and facing right: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . W W . # . . . . . W[F]W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Finding a flagged node, it reverses direction and cleans the node: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . W W . # . . . . .[W]. W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . The weakened node becomes infected, and it continues in the same direction: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . W W . # . . . .[.]# . W . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Of the first 100 bursts, 26 will result in infection. Unfortunately, another feature of this evolved virus is speed; of the first 10000000 bursts, 2511944 will result in infection. Given your actual map, after 10000000 bursts of activity, how many bursts cause a node to become infected? (Do not count nodes that begin infected.)
285
--- Day 24: It Hangs in the Balance --- It's Christmas Eve, and Santa is loading up the sleigh for this year's deliveries. However, there's one small problem: he can't get the sleigh to balance. If it isn't balanced, he can't defy physics, and nobody gets presents this year. No pressure. Santa has provided you a list of the weights of every package he needs to fit on the sleigh. The packages need to be split into three groups of exactly the same weight, and every package has to fit. The first group goes in the passenger compartment of the sleigh, and the second and third go in containers on either side. Only when all three groups weigh exactly the same amount will the sleigh be able to fly. Defying physics has rules, you know! Of course, that's not the only problem. The first group - the one going in the passenger compartment - needs as few packages as possible so that Santa has some legroom left over. It doesn't matter how many packages are in either of the other two groups, so long as all of the groups weigh the same. Furthermore, Santa tells you, if there are multiple ways to arrange the packages such that the fewest possible are in the first group, you need to choose the way where the first group has the smallest quantum entanglement to reduce the chance of any "complications". The quantum entanglement of a group of packages is the product of their weights, that is, the value you get when you multiply their weights together. Only consider quantum entanglement if the first group has the fewest possible number of packages in it and all groups weigh the same amount. For example, suppose you have ten packages with weights 1 through 5 and 7 through 11. For this situation, some of the unique first groups, their quantum entanglements, and a way to divide the remaining packages are as follows: Group 1; Group 2; Group 3 11 9 (QE= 99); 10 8 2; 7 5 4 3 1 10 9 1 (QE= 90); 11 7 2; 8 5 4 3 10 8 2 (QE=160); 11 9; 7 5 4 3 1 10 7 3 (QE=210); 11 9; 8 5 4 2 1 10 5 4 1 (QE=200); 11 9; 8 7 3 2 10 5 3 2 (QE=300); 11 9; 8 7 4 1 10 4 3 2 1 (QE=240); 11 9; 8 7 5 9 8 3 (QE=216); 11 7 2; 10 5 4 1 9 7 4 (QE=252); 11 8 1; 10 5 3 2 9 5 4 2 (QE=360); 11 8 1; 10 7 3 8 7 5 (QE=280); 11 9; 10 4 3 2 1 8 5 4 3 (QE=480); 11 9; 10 7 2 1 7 5 4 3 1 (QE=420); 11 9; 10 8 2 Of these, although 10 9 1 has the smallest quantum entanglement (90), the configuration with only two packages, 11 9, in the passenger compartment gives Santa the most legroom and wins. In this situation, the quantum entanglement for the ideal configuration is therefore 99. Had there been two configurations with only two packages in the first group, the one with the smaller quantum entanglement would be chosen. What is the quantum entanglement of the first group of packages in the ideal configuration?
286
--- Day 5: Sunny with a Chance of Asteroids --- You're starting to sweat as the ship makes its way toward Mercury. The Elves suggest that you get the air conditioner working by upgrading your ship computer to support the Thermal Environment Supervision Terminal. The Thermal Environment Supervision Terminal (TEST) starts by running a diagnostic program (your puzzle input). The TEST diagnostic program will run on your existing Intcode computer after a few modifications: First, you'll need to add two new instructions: Opcode 3 takes a single integer as input and saves it to the position given by its only parameter. For example, the instruction 3,50 would take an input value and store it at address 50. Opcode 4 outputs the value of its only parameter. For example, the instruction 4,50 would output the value at address 50. Programs that use these instructions will come with documentation that explains what should be connected to the input and output. The program 3,0,4,0,99 outputs whatever it gets as input, then halts. Second, you'll need to add support for parameter modes: Each parameter of an instruction is handled based on its parameter mode. Right now, your ship computer already understands parameter mode 0, position mode, which causes the parameter to be interpreted as a position - if the parameter is 50, its value is the value stored at address 50 in memory. Until now, all parameters have been in position mode. Now, your ship computer will also need to handle parameters in mode 1, immediate mode. In immediate mode, a parameter is interpreted as a value - if the parameter is 50, its value is simply 50. Parameter modes are stored in the same value as the instruction's opcode. The opcode is a two-digit number based only on the ones and tens digit of the value, that is, the opcode is the rightmost two digits of the first value in an instruction. Parameter modes are single digits, one per parameter, read right-to-left from the opcode: the first parameter's mode is in the hundreds digit, the second parameter's mode is in the thousands digit, the third parameter's mode is in the ten-thousands digit, and so on. Any missing modes are 0. For example, consider the program 1002,4,3,4,33. The first instruction, 1002,4,3,4, is a multiply instruction - the rightmost two digits of the first value, 02, indicate opcode 2, multiplication. Then, going right to left, the parameter modes are 0 (hundreds digit), 1 (thousands digit), and 0 (ten-thousands digit, not present and therefore zero): ABCDE 1002 DE - two-digit opcode, 02 == opcode 2 C - mode of 1st parameter, 0 == position mode B - mode of 2nd parameter, 1 == immediate mode A - mode of 3rd parameter, 0 == position mode, omitted due to being a leading zero This instruction multiplies its first two parameters. The first parameter, 4 in position mode, works like it did before - its value is the value stored at address 4 (33). The second parameter, 3 in immediate mode, simply has value 3. The result of this operation, 33 * 3 = 99, is written according to the third parameter, 4 in position mode, which also works like it did before - 99 is written to address 4. Parameters that an instruction writes to will never be in immediate mode. Finally, some notes: It is important to remember that the instruction pointer should increase by the number of values in the instruction after the instruction finishes. Because of the new instructions, this amount is no longer always 4. Integers can be negative: 1101,100,-1,4,0 is a valid program (find 100 + -1, store the result in position 4). The TEST diagnostic program will start by requesting from the user the ID of the system to test by running an input instruction - provide it 1, the ID for the ship's air conditioner unit. It will then perform a series of diagnostic tests confirming that various parts of the Intcode computer, like parameter modes, function correctly. For each test, it will run an output instruction indicating how far the result of the test was from the expected value, where 0 means the test was successful. Non-zero outputs mean that a function is not working correctly; check the instructions that were run before the output instruction to see which one failed. Finally, the program will output a diagnostic code and immediately halt. This final output isn't an error; an output followed immediately by a halt means the program finished. If all outputs were zero except the diagnostic code, the diagnostic program ran successfully. After providing 1 to the only input instruction and passing all the tests, what diagnostic code does the program produce?
287
--- Day 3: Binary Diagnostic --- The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic report just in case. The diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things about the conditions of the submarine. The first parameter to check is the power consumption. You need to use the binary numbers in the diagnostic report to generate two new binary numbers (called the gamma rate and the epsilon rate). The power consumption can then be found by multiplying the gamma rate by the epsilon rate. Each bit in the gamma rate can be determined by finding the most common bit in the corresponding position of all numbers in the diagnostic report. For example, given the following diagnostic report: 00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 Considering only the first bit of each number, there are five 0 bits and seven 1 bits. Since the most common bit is 1, the first bit of the gamma rate is 1. The most common second bit of the numbers in the diagnostic report is 0, so the second bit of the gamma rate is 0. The most common value of the third, fourth, and fifth bits are 1, 1, and 0, respectively, and so the final three bits of the gamma rate are 110. So, the gamma rate is the binary number 10110, or 22 in decimal. The epsilon rate is calculated in a similar way; rather than use the most common bit, the least common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal. Multiplying the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198. Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate, then multiply them together. What is the power consumption of the submarine? (Be sure to represent your answer in decimal, not binary.) Your puzzle answer was 1540244. --- Part Two --- Next, you should verify the life support rating, which can be determined by multiplying the oxygen generator rating by the CO2 scrubber rating. Both the oxygen generator rating and the CO2 scrubber rating are values that can be found in your diagnostic report - finding them is the tricky part. Both values are located using a similar process that involves filtering out values until only one remains. Before searching for either rating value, start with the full list of binary numbers from your diagnostic report and consider just the first bit of those numbers. Then: Keep only numbers selected by the bit criteria for the type of rating value for which you are searching. Discard numbers which do not match the bit criteria. If you only have one number left, stop; this is the rating value for which you are searching. Otherwise, repeat the process, considering the next bit to the right. The bit criteria depends on which type of rating value you want to find: To find oxygen generator rating, determine the most common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 1 in the position being considered. To find CO2 scrubber rating, determine the least common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 0 in the position being considered. For example, to determine the oxygen generator rating value using the same example diagnostic report from above: Start with all 12 numbers and consider only the first bit of each number. There are more 1 bits (7) than 0 bits (5), so keep only the 7 numbers with a 1 in the first position: 11110, 10110, 10111, 10101, 11100, 10000, and 11001. Then, consider the second bit of the 7 remaining numbers: there are more 0 bits (4) than 1 bits (3), so keep only the 4 numbers with a 0 in the second position: 10110, 10111, 10101, and 10000. In the third position, three of the four numbers have a 1, so keep those three: 10110, 10111, and 10101. In the fourth position, two of the three numbers have a 1, so keep those two: 10110 and 10111. In the fifth position, there are an equal number of 0 bits and 1 bits (one each). So, to find the oxygen generator rating, keep the number with a 1 in that position: 10111. As there is only one number left, stop; the oxygen generator rating is 10111, or 23 in decimal. Then, to determine the CO2 scrubber rating value from the same example above: Start again with all 12 numbers and consider only the first bit of each number. There are fewer 0 bits (5) than 1 bits (7), so keep only the 5 numbers with a 0 in the first position: 00100, 01111, 00111, 00010, and 01010. Then, consider the second bit of the 5 remaining numbers: there are fewer 1 bits (2) than 0 bits (3), so keep only the 2 numbers with a 1 in the second position: 01111 and 01010. In the third position, there are an equal number of 0 bits and 1 bits (one each). So, to find the CO2 scrubber rating, keep the number with a 0 in that position: 01010. As there is only one number left, stop; the CO2 scrubber rating is 01010, or 10 in decimal. Finally, to find the life support rating, multiply the oxygen generator rating (23) by the CO2 scrubber rating (10) to get 230. Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating, then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in decimal, not binary.)
288
--- Day 11: Seating System --- Your plane lands with plenty of time to spare. The final leg of your journey is a ferry that goes directly to the tropical island where you can finally start your vacation. As you reach the waiting area to board the ferry, you realize you're so early, nobody else has even arrived yet! By modeling the process people use to choose (or abandon) their seat in the waiting area, you're pretty sure you can predict the best place to sit. You make a quick map of the seat layout (your puzzle input). The seat layout fits neatly on a grid. Each position is either floor (.), an empty seat (L), or an occupied seat (#). For example, the initial seat layout might look like this: L.LL.LL.LL LLLLLLL.LL L.L.L..L.. LLLL.LL.LL L.LL.LL.LL L.LLLLL.LL ..L.L..... LLLLLLLLLL L.LLLLLL.L L.LLLLL.LL Now, you just need to model the people who will be arriving shortly. Fortunately, people are entirely predictable and always follow a simple set of rules. All decisions are based on the number of occupied seats adjacent to a given seat (one of the eight positions immediately up, down, left, right, or diagonal from the seat). The following rules are applied to every seat simultaneously: If a seat is empty (L) and there are no occupied seats adjacent to it, the seat becomes occupied. If a seat is occupied (#) and four or more seats adjacent to it are also occupied, the seat becomes empty. Otherwise, the seat's state does not change. Floor (.) never changes; seats don't move, and nobody sits on the floor. After one round of these rules, every seat in the example layout becomes occupied: #.##.##.## #######.## #.#.#..#.. ####.##.## #.##.##.## #.#####.## ..#.#..... ########## #.######.# #.#####.## After a second round, the seats with four or more occupied adjacent seats become empty again: #.LL.L#.## #LLLLLL.L# L.L.L..L.. #LLL.LL.L# #.LL.LL.LL #.LLLL#.## ..L.L..... #LLLLLLLL# #.LLLLLL.L #.#LLLL.## This process continues for three more rounds: #.##.L#.## #L###LL.L# L.#.#..#.. #L##.##.L# #.##.LL.LL #.###L#.## ..#.#..... #L######L# #.LL###L.L #.#L###.## #.#L.L#.## #LLL#LL.L# L.L.L..#.. #LLL.##.L# #.LL.LL.LL #.LL#L#.## ..L.L..... #L#LLLL#L# #.LLLLLL.L #.#L#L#.## #.#L.L#.## #LLL#LL.L# L.#.L..#.. #L##.##.L# #.#L.LL.LL #.#L#L#.## ..L.L..... #L#L##L#L# #.LLLLLL.L #.#L#L#.## At this point, something interesting happens: the chaos stabilizes and further applications of these rules cause no seats to change state! Once people stop moving around, you count 37 occupied seats. Simulate your seating area by applying the seating rules repeatedly until no seats change state. How many seats end up occupied?
289
--- Day 4: Repose Record --- You've sneaked into another supply closet - this time, it's across from the prototype suit manufacturing lab. You need to sneak inside and fix the issues with the suit, but there's a guard stationed outside the lab, so this is as close as you can safely get. As you search the closet for anything that might help, you discover that you're not the first person to want to sneak in. Covering the walls, someone has spent an hour starting every midnight for the past few months secretly observing this guard post! They've been writing down the ID of the one guard on duty that night - the Elves seem to have decided that one guard was enough for the overnight shift - as well as when they fall asleep or wake up while at their post (your puzzle input). For example, consider the following records, which have already been organized into chronological order: [1518-11-01 00:00] Guard #10 begins shift [1518-11-01 00:05] falls asleep [1518-11-01 00:25] wakes up [1518-11-01 00:30] falls asleep [1518-11-01 00:55] wakes up [1518-11-01 23:58] Guard #99 begins shift [1518-11-02 00:40] falls asleep [1518-11-02 00:50] wakes up [1518-11-03 00:05] Guard #10 begins shift [1518-11-03 00:24] falls asleep [1518-11-03 00:29] wakes up [1518-11-04 00:02] Guard #99 begins shift [1518-11-04 00:36] falls asleep [1518-11-04 00:46] wakes up [1518-11-05 00:03] Guard #99 begins shift [1518-11-05 00:45] falls asleep [1518-11-05 00:55] wakes up Timestamps are written using year-month-day hour:minute format. The guard falling asleep or waking up is always the one whose shift most recently started. Because all asleep/awake times are during the midnight hour (00:00 - 00:59), only the minute portion (00 - 59) is relevant for those events. Visually, these records show that the guards are asleep at these times: Date ID Minute 000000000011111111112222222222333333333344444444445555555555 012345678901234567890123456789012345678901234567890123456789 11-01 #10 .....####################.....#########################..... 11-02 #99 ........................................##########.......... 11-03 #10 ........................#####............................... 11-04 #99 ....................................##########.............. 11-05 #99 .............................................##########..... The columns are Date, which shows the month-day portion of the relevant day; ID, which shows the guard on duty that day; and Minute, which shows the minutes during which the guard was asleep within the midnight hour. (The Minute column's header shows the minute's ten's digit in the first row and the one's digit in the second row.) Awake is shown as ., and asleep is shown as #. Note that guards count as asleep on the minute they fall asleep, and they count as awake on the minute they wake up. For example, because Guard #10 wakes up at 00:25 on 1518-11-01, minute 25 is marked as awake. If you can figure out the guard most likely to be asleep at a specific time, you might be able to trick that guard into working tonight so you can have the best chance of sneaking in. You have two strategies for choosing the best guard/minute combination. Strategy 1: Find the guard that has the most minutes asleep. What minute does that guard spend asleep the most? In the example above, Guard #10 spent the most minutes asleep, a total of 50 minutes (20+25+5), while Guard #99 only slept for a total of 30 minutes (10+10+10). Guard #10 was asleep most during minute 24 (on two days, whereas any other minute the guard was asleep was only seen on one day). While this example listed the entries in chronological order, your entries are in the order you found them. You'll need to organize them before they can be analyzed. What is the ID of the guard you chose multiplied by the minute you chose? (In the above example, the answer would be 10 * 24 = 240.) Your puzzle answer was 35184. --- Part Two --- Strategy 2: Of all guards, which guard is most frequently asleep on the same minute? In the example above, Guard #99 spent minute 45 asleep more than any other guard or minute - three times in total. (In all other cases, any guard spent any minute asleep at most twice.) What is the ID of the guard you chose multiplied by the minute you chose? (In the above example, the answer would be 99 * 45 = 4455.)
290
--- Day 8: Seven Segment Search --- You barely reach the safety of the cave when the whale smashes into the cave mouth, collapsing it. Sensors indicate another exit to this cave at a much greater depth, so you have no choice but to press on. As your submarine slowly makes its way through the cave system, you notice that the four-digit seven-segment displays in your submarine are malfunctioning; they must have been damaged during the escape. You'll be in a lot of trouble without them, so you'd better figure out what's wrong. Each digit of a seven-segment display is rendered by turning on or off any of seven segments named a through g: 0: 1: 2: 3: 4: aaaa .... aaaa aaaa .... b c . c . c . c b c b c . c . c . c b c .... .... dddd dddd dddd e f . f e . . f . f e f . f e . . f . f gggg .... gggg gggg .... 5: 6: 7: 8: 9: aaaa aaaa aaaa aaaa aaaa b . b . . c b c b c b . b . . c b c b c dddd dddd .... dddd dddd . f e f . f e f . f . f e f . f e f . f gggg gggg .... gggg gggg So, to render a 1, only segments c and f would be turned on; the rest would be off. To render a 7, only segments a, c, and f would be turned on. The problem is that the signals which control the segments have been mixed up on each display. The submarine is still trying to display numbers by producing output on signal wires a through g, but those wires are connected to segments randomly. Worse, the wire/segment connections are mixed up separately for each four-digit display! (All of the digits within a display use the same connections, though.) So, you might know that only signal wires b and g are turned on, but that doesn't mean segments b and g are turned on: the only digit that uses two segments is 1, so it must mean segments c and f are meant to be on. With just that information, you still can't tell which wire (b/g) goes to which segment (c/f). For that, you'll need to collect more information. For each display, you watch the changing signals for a while, make a note of all ten unique signal patterns you see, and then write down a single four digit output value (your puzzle input). Using the signal patterns, you should be able to work out which pattern corresponds to which digit. For example, here is what you might see in a single entry in your notes: acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf (The entry is wrapped here to two lines so it fits; in your notes, it will all be on a single line.) Each entry consists of ten unique signal patterns, a | delimiter, and finally the four digit output value. Within an entry, the same wire/segment connections are used (but you don't know what the connections actually are). The unique signal patterns correspond to the ten different ways the submarine tries to render a digit using the current wire/segment connections. Because 7 is the only digit that uses three segments, dab in the above example means that to render a 7, signal lines d, a, and b are on. Because 4 is the only digit that uses four segments, eafb means that to render a 4, signal lines e, a, f, and b are on. Using this information, you should be able to work out which combination of signal wires corresponds to each of the ten digits. Then, you can decode the four digit output value. Unfortunately, in the above example, all of the digits in the output value (cdfeb fcadb cdfeb cdbaf) use five segments and are more difficult to deduce. For now, focus on the easy digits. Consider this larger example: be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce Because the digits 1, 4, 7, and 8 each use a unique number of segments, you should be able to tell which combinations of signals correspond to those digits. Counting only digits in the output values (the part after | on each line), in the above example, there are 26 instances of digits that use a unique number of segments (highlighted above). In the output values, how many times do digits 1, 4, 7, or 8 appear? Your puzzle answer was 525. --- Part Two --- Through a little deduction, you should now be able to determine the remaining digits. Consider again the first example above: acedgfb cdfbe gcdfa fbcad dab cefabd cdfgeb eafb cagedb ab | cdfeb fcadb cdfeb cdbaf After some careful analysis, the mapping between signal wires and segments only make sense in the following configuration: dddd e a e a ffff g b g b cccc So, the unique signal patterns would correspond to the following digits: acedgfb: 8 cdfbe: 5 gcdfa: 2 fbcad: 3 dab: 7 cefabd: 9 cdfgeb: 6 eafb: 4 cagedb: 0 ab: 1 Then, the four digits of the output value can be decoded: cdfeb: 5 fcadb: 3 cdfeb: 5 cdbaf: 3 Therefore, the output value for this entry is 5353. Following this same process for each entry in the second, larger example above, the output value of each entry can be determined: fdgacbe cefdb cefbgd gcbe: 8394 fcgedb cgb dgebacf gc: 9781 cg cg fdcagb cbg: 1197 efabcd cedba gadfec cb: 9361 gecf egdcabf bgf bfgea: 4873 gebdcfa ecba ca fadegcb: 8418 cefg dcbef fcge gbcadfe: 4548 ed bcgafe cdgba cbgef: 1625 gbdfcae bgc cg cgb: 8717 fgae cfgab fg bagce: 4315 Adding all of the output values in this larger example produces 61229. For each entry, determine all of the wire/segment connections and decode the four-digit output values. What do you get if you add up all of the output values?
291
--- Day 4: Passport Processing --- You arrive at the airport only to realize that you grabbed your North Pole Credentials instead of your passport. While these documents are extremely similar, North Pole Credentials aren't issued by a country and therefore aren't actually valid documentation for travel in most of the world. It seems like you're not the only one having problems, though; a very long line has formed for the automatic passport scanners, and the delay could upset your travel itinerary. Due to some questionable network security, you realize you might be able to solve both of these problems at the same time. The automatic passport scanners are slow because they're having trouble detecting which passports have all required fields. The expected fields are as follows: byr (Birth Year) iyr (Issue Year) eyr (Expiration Year) hgt (Height) hcl (Hair Color) ecl (Eye Color) pid (Passport ID) cid (Country ID) Passport data is validated in batch files (your puzzle input). Each passport is represented as a sequence of key:value pairs separated by spaces or newlines. Passports are separated by blank lines. Here is an example batch file containing four passports: ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in The first passport is valid - all eight fields are present. The second passport is invalid - it is missing hgt (the Height field). The third passport is interesting; the only missing field is cid, so it looks like data from North Pole Credentials, not a passport at all! Surely, nobody would mind if you made the system temporarily ignore missing cid fields. Treat this "passport" as valid. The fourth passport is missing two fields, cid and byr. Missing cid is fine, but missing any other field is not, so this passport is invalid. According to the above rules, your improved system would report 2 valid passports. Count the number of valid passports - those that have all required fields. Treat cid as optional. In your batch file, how many passports are valid? Your puzzle answer was 226. --- Part Two --- The line is moving more quickly now, but you overhear airport security talking about how passports with invalid data are getting through. Better add some data validation, quick! You can continue to ignore the cid field, but each other field has strict rules about what values are valid for automatic validation: byr (Birth Year) - four digits; at least 1920 and at most 2002. iyr (Issue Year) - four digits; at least 2010 and at most 2020. eyr (Expiration Year) - four digits; at least 2020 and at most 2030. hgt (Height) - a number followed by either cm or in: If cm, the number must be at least 150 and at most 193. If in, the number must be at least 59 and at most 76. hcl (Hair Color) - a # followed by exactly six characters 0-9 or a-f. ecl (Eye Color) - exactly one of: amb blu brn gry grn hzl oth. pid (Passport ID) - a nine-digit number, including leading zeroes. cid (Country ID) - ignored, missing or not. Your job is to count the passports where all required fields are both present and valid according to the above rules. Here are some example values: byr valid: 2002 byr invalid: 2003 hgt valid: 60in hgt valid: 190cm hgt invalid: 190in hgt invalid: 190 hcl valid: #123abc hcl invalid: #123abz hcl invalid: 123abc ecl valid: brn ecl invalid: wat pid valid: 000000001 pid invalid: 0123456789 Here are some invalid passports: eyr:1972 cid:100 hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 iyr:2019 hcl:#602927 eyr:1967 hgt:170cm ecl:grn pid:012533040 byr:1946 hcl:dab227 iyr:2012 ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 hgt:59cm ecl:zzz eyr:2038 hcl:74454a iyr:2023 pid:3556412378 byr:2007 Here are some valid passports: pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f eyr:2029 ecl:blu cid:129 byr:1989 iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm hcl:#888785 hgt:164cm byr:2001 iyr:2015 cid:88 pid:545766238 ecl:hzl eyr:2022 iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719 Count the number of valid passports - those that have all required fields and valid values. Continue to treat cid as optional. In your batch file, how many passports are valid?
292
--- Day 9: Rope Bridge --- This rope bridge creaks as you walk along it. You aren't sure how old it is, or whether it can even support your weight. It seems to support the Elves just fine, though. The bridge spans a gorge which was carved out by the massive river far below you. You step carefully; as you do, the ropes stretch and twist. You decide to distract yourself by modeling rope physics; maybe you can even figure out where not to step. Consider a rope with a knot at each end; these knots mark the head and the tail of the rope. If the head moves far enough away from the tail, the tail is pulled toward the head. Due to nebulous reasoning involving Planck lengths, you should be able to model the positions of the knots on a two-dimensional grid. Then, by following a hypothetical series of motions (your puzzle input) for the head, you can determine how the tail will move. Due to the aforementioned Planck lengths, the rope must be quite short; in fact, the head (H) and tail (T) must always be touching (diagonally adjacent and even overlapping both count as touching): .... .TH. .... .... .H.. ..T. .... ... .H. (H covers T) ... If the head is ever two steps directly up, down, left, or right from the tail, the tail must also move one step in that direction so it remains close enough: ..... ..... ..... .TH.. -> .T.H. -> ..TH. ..... ..... ..... ... ... ... .T. .T. ... .H. -> ... -> .T. ... .H. .H. ... ... ... Otherwise, if the head and tail aren't touching and aren't in the same row or column, the tail always moves one step diagonally to keep up: ..... ..... ..... ..... ..H.. ..H.. ..H.. -> ..... -> ..T.. .T... .T... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..... ..H.. -> ...H. -> ..TH. .T... .T... ..... ..... ..... ..... You just need to work out where the tail goes as the head follows a series of motions. Assume the head and the tail both start at the same position, overlapping. For example: R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2 This series of motions moves the head right four steps, then up four steps, then left three steps, then down one step, and so on. After each step, you'll need to update the position of the tail if the step means the head is no longer adjacent to the tail. Visually, these motions occur as follows (s marks the starting position as a reference point): == Initial State == ...... ...... ...... ...... H..... (H covers T, s) == R 4 == ...... ...... ...... ...... TH.... (T covers s) ...... ...... ...... ...... sTH... ...... ...... ...... ...... s.TH.. ...... ...... ...... ...... s..TH. == U 4 == ...... ...... ...... ....H. s..T.. ...... ...... ....H. ....T. s..... ...... ....H. ....T. ...... s..... ....H. ....T. ...... ...... s..... == L 3 == ...H.. ....T. ...... ...... s..... ..HT.. ...... ...... ...... s..... .HT... ...... ...... ...... s..... == D 1 == ..T... .H.... ...... ...... s..... == R 4 == ..T... ..H... ...... ...... s..... ..T... ...H.. ...... ...... s..... ...... ...TH. ...... ...... s..... ...... ....TH ...... ...... s..... == D 1 == ...... ....T. .....H ...... s..... == L 5 == ...... ....T. ....H. ...... s..... ...... ....T. ...H.. ...... s..... ...... ...... ..HT.. ...... s..... ...... ...... .HT... ...... s..... ...... ...... HT.... ...... s..... == R 2 == ...... ...... .H.... (H covers T) ...... s..... ...... ...... .TH... ...... s..... After simulating the rope, you can count up all of the positions the tail visited at least once. In this diagram, s again marks the starting position (which the tail also visited) and # marks other positions the tail visited: ..##.. ...##. .####. ....#. s###.. So, there are 13 positions the tail visited at least once. Simulate your complete hypothetical series of motions. How many positions does the tail of the rope visit at least once?
293
--- Day 19: Medicine for Rudolph --- Rudolph the Red-Nosed Reindeer is sick! His nose isn't shining very brightly, and he needs medicine. Red-Nosed Reindeer biology isn't similar to regular reindeer biology; Rudolph is going to need custom-made medicine. Unfortunately, Red-Nosed Reindeer chemistry isn't similar to regular reindeer chemistry, either. The North Pole is equipped with a Red-Nosed Reindeer nuclear fusion/fission plant, capable of constructing any Red-Nosed Reindeer molecule you need. It works by starting with some input molecule and then doing a series of replacements, one per step, until it has the right molecule. However, the machine has to be calibrated before it can be used. Calibration involves determining the number of molecules that can be generated in one step from a given starting point. For example, imagine a simpler machine that supports only the following replacements: H => HO H => OH O => HH Given the replacements above and starting with HOH, the following molecules could be generated: HOOH (via H => HO on the first H). HOHO (via H => HO on the second H). OHOH (via H => OH on the first H). HOOH (via H => OH on the second H). HHHH (via O => HH). So, in the example above, there are 4 distinct molecules (not five, because HOOH appears twice) after one replacement from HOH. Santa's favorite molecule, HOHOHO, can become 7 distinct molecules (over nine replacements: six from H, and three from O). The machine replaces without regard for the surrounding characters. For example, given the string H2O, the transition H => OO would result in OO2O. Your puzzle input describes all of the possible replacements and, at the bottom, the medicine molecule for which you need to calibrate the machine. How many distinct molecules can be created after all the different ways you can do one replacement on the medicine molecule?
294
--- Day 3: Toboggan Trajectory --- With the toboggan login problems resolved, you set off toward the airport. While travel by toboggan might be easy, it's certainly not safe: there's very minimal steering and the area is covered in trees. You'll need to see which angles will take you near the fewest trees. Due to the local geology, trees in this area only grow on exact integer coordinates in a grid. You make a map (your puzzle input) of the open squares (.) and trees (#) you can see. For example: ..##....... #...#...#.. .#....#..#. ..#.#...#.# .#...##..#. ..#.##..... .#.#.#....# .#........# #.##...#... #...##....# .#..#...#.# These aren't the only trees, though; due to something you read about once involving arboreal genetics and biome stability, the same pattern repeats to the right many times: ..##.........##.........##.........##.........##.........##....... ---> #...#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#.. .#....#..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#. ..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.# .#...##..#..#...##..#..#...##..#..#...##..#..#...##..#..#...##..#. ..#.##.......#.##.......#.##.......#.##.......#.##.......#.##..... ---> .#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....# .#........#.#........#.#........#.#........#.#........#.#........# #.##...#...#.##...#...#.##...#...#.##...#...#.##...#...#.##...#... #...##....##...##....##...##....##...##....##...##....##...##....# .#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.#.#..#...#.# ---> You start on the open square (.) in the top-left corner and need to reach the bottom (below the bottom-most row on your map). The toboggan can only follow a few specific slopes (you opted for a cheaper model that prefers rational numbers); start by counting all the trees you would encounter for the slope right 3, down 1: From your starting position at the top-left, check the position that is right 3 and down 1. Then, check the position that is right 3 and down 1 from there, and so on until you go past the bottom of the map. The locations you'd check in the above example are marked here with O where there was an open square and X where there was a tree: ..##.........##.........##.........##.........##.........##....... ---> #..O#...#..#...#...#..#...#...#..#...#...#..#...#...#..#...#...#.. .#....X..#..#....#..#..#....#..#..#....#..#..#....#..#..#....#..#. ..#.#...#O#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.#..#.#...#.# .#...##..#..X...##..#..#...##..#..#...##..#..#...##..#..#...##..#. ..#.##.......#.X#.......#.##.......#.##.......#.##.......#.##..... ---> .#.#.#....#.#.#.#.O..#.#.#.#....#.#.#.#....#.#.#.#....#.#.#.#....# .#........#.#........X.#........#.#........#.#........#.#........# #.##...#...#.##...#...#.X#...#...#.##...#...#.##...#...#.##...#... #...##....##...##....##...#X....##...##....##...##....##...##....# .#..#...#.#.#..#...#.#.#..#...X.#.#..#...#.#.#..#...#.#.#..#...#.# ---> In this example, traversing the map using this slope would cause you to encounter 7 trees. Starting at the top-left corner of your map and following a slope of right 3 and down 1, how many trees would you encounter? Your puzzle answer was 171. --- Part Two --- Time to check the rest of the slopes - you need to minimize the probability of a sudden arboreal stop, after all. Determine the number of trees you would encounter if, for each of the following slopes, you start at the top-left corner and traverse the map all the way to the bottom: Right 1, down 1. Right 3, down 1. (This is the slope you already checked.) Right 5, down 1. Right 7, down 1. Right 1, down 2. In the above example, these slopes would find 2, 7, 3, 4, and 2 tree(s) respectively; multiplied together, these produce the answer 336. What do you get if you multiply together the number of trees encountered on each of the listed slopes?
295
--- Day 22: Grid Computing --- You gain access to a massive storage cluster arranged in a grid; each storage node is only connected to the four nodes directly adjacent to it (three if the node is on an edge, two if it's in a corner). You can directly access data only on node /dev/grid/node-x0-y0, but you can perform some limited actions on the other nodes: You can get the disk usage of all nodes (via df). The result of doing this is in your puzzle input. You can instruct a node to move (not copy) all of its data to an adjacent node (if the destination node has enough space to receive the data). The sending node is left empty after this operation. Nodes are named by their position: the node named node-x10-y10 is adjacent to nodes node-x9-y10, node-x11-y10, node-x10-y9, and node-x10-y11. Before you begin, you need to understand the arrangement of data on these nodes. Even though you can only move data between directly connected nodes, you're going to need to rearrange a lot of the data to get access to the data you need. Therefore, you need to work out how you might be able to shift data around. To do this, you'd like to count the number of viable pairs of nodes. A viable pair is any two nodes (A,B), regardless of whether they are directly connected, such that: Node A is not empty (its Used is not zero). Nodes A and B are not the same node. The data on node A (its Used) would fit on node B (its Avail). How many viable pairs of nodes are there?
296
--- Day 6: Lanternfish --- The sea floor is getting steeper. Maybe the sleigh keys got carried this way? A massive school of glowing lanternfish swims past. They must spawn quickly to reach such large numbers - maybe exponentially quickly? You should model their growth rate to be sure. Although you know nothing about this specific species of lanternfish, you make some guesses about their attributes. Surely, each lanternfish creates a new lanternfish once every 7 days. However, this process isn't necessarily synchronized between every lanternfish - one lanternfish might have 2 days left until it creates another lanternfish, while another might have 4. So, you can model each fish as a single number that represents the number of days until it creates a new lanternfish. Furthermore, you reason, a new lanternfish would surely need slightly longer before it's capable of producing more lanternfish: two more days for its first cycle. So, suppose you have a lanternfish with an internal timer value of 3: After one day, its internal timer would become 2. After another day, its internal timer would become 1. After another day, its internal timer would become 0. After another day, its internal timer would reset to 6, and it would create a new lanternfish with an internal timer of 8. After another day, the first lanternfish would have an internal timer of 5, and the second lanternfish would have an internal timer of 7. A lanternfish that creates a new fish resets its timer to 6, not 7 (because 0 is included as a valid timer value). The new lanternfish starts with an internal timer of 8 and does not start counting down until the next day. Realizing what you're trying to do, the submarine automatically produces a list of the ages of several hundred nearby lanternfish (your puzzle input). For example, suppose you were given the following list: 3,4,3,1,2 This list means that the first fish has an internal timer of 3, the second fish has an internal timer of 4, and so on until the fifth fish, which has an internal timer of 2. Simulating these fish over several days would proceed as follows: Initial state: 3,4,3,1,2 After 1 day: 2,3,2,0,1 After 2 days: 1,2,1,6,0,8 After 3 days: 0,1,0,5,6,7,8 After 4 days: 6,0,6,4,5,6,7,8,8 After 5 days: 5,6,5,3,4,5,6,7,7,8 After 6 days: 4,5,4,2,3,4,5,6,6,7 After 7 days: 3,4,3,1,2,3,4,5,5,6 After 8 days: 2,3,2,0,1,2,3,4,4,5 After 9 days: 1,2,1,6,0,1,2,3,3,4,8 After 10 days: 0,1,0,5,6,0,1,2,2,3,7,8 After 11 days: 6,0,6,4,5,6,0,1,1,2,6,7,8,8,8 After 12 days: 5,6,5,3,4,5,6,0,0,1,5,6,7,7,7,8,8 After 13 days: 4,5,4,2,3,4,5,6,6,0,4,5,6,6,6,7,7,8,8 After 14 days: 3,4,3,1,2,3,4,5,5,6,3,4,5,5,5,6,6,7,7,8 After 15 days: 2,3,2,0,1,2,3,4,4,5,2,3,4,4,4,5,5,6,6,7 After 16 days: 1,2,1,6,0,1,2,3,3,4,1,2,3,3,3,4,4,5,5,6,8 After 17 days: 0,1,0,5,6,0,1,2,2,3,0,1,2,2,2,3,3,4,4,5,7,8 After 18 days: 6,0,6,4,5,6,0,1,1,2,6,0,1,1,1,2,2,3,3,4,6,7,8,8,8,8 Each day, a 0 becomes a 6 and adds a new 8 to the end of the list, while each other number decreases by 1 if it was present at the start of the day. In this example, after 18 days, there are a total of 26 fish. After 80 days, there would be a total of 5934. Find a way to simulate lanternfish. How many lanternfish would there be after 80 days?
297
--- Day 1: Not Quite Lisp --- Santa was hoping for a white Christmas, but his weather machine's "snow" function is powered by stars, and he's fresh out! To save Christmas, he needs you to collect fifty stars by December 25th. Collect stars by helping Santa solve puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! Here's an easy puzzle to warm you up. Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time. An opening parenthesis, (, means he should go up one floor, and a closing parenthesis, ), means he should go down one floor. The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors. For example: (()) and ()() both result in floor 0. ((( and (()(()( both result in floor 3. ))((((( also results in floor 3. ()) and ))( both result in floor -1 (the first basement level). ))) and )())()) both result in floor -3. To what floor do the instructions take Santa? Your puzzle answer was 280. --- Part Two --- Now, given the same instructions, find the position of the first character that causes him to enter the basement (floor -1). The first character in the instructions has position 1, the second character has position 2, and so on. For example: ) causes him to enter the basement at character position 1. ()()) causes him to enter the basement at character position 5. What is the position of the character that causes Santa to first enter the basement?
298
--- Day 13: Packet Scanners --- You need to cross a vast firewall. The firewall consists of several layers, each with a security scanner that moves back and forth across the layer. To succeed, you must not be detected by a scanner. By studying the firewall briefly, you are able to record (in your puzzle input) the depth of each layer and the range of the scanning area for the scanner within it, written as depth: range. Each layer has a thickness of exactly 1. A layer at depth 0 begins immediately inside the firewall; a layer at depth 1 would start immediately after that. For example, suppose you've recorded the following: 0: 3 1: 2 4: 4 6: 4 This means that there is a layer immediately inside the firewall (with range 3), a second layer immediately after that (with range 2), a third layer which begins at depth 4 (with range 4), and a fourth layer which begins at depth 6 (also with range 4). Visually, it might look like this: 0 1 2 3 4 5 6 [ ] [ ] ... ... [ ] ... [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] Within each layer, a security scanner moves back and forth within its range. Each security scanner starts at the top and moves down until it reaches the bottom, then moves up until it reaches the top, and repeats. A security scanner takes one picosecond to move one step. Drawing scanners as S, the first few picoseconds look like this: Picosecond 0: 0 1 2 3 4 5 6 [S] [S] ... ... [S] ... [S] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] Picosecond 1: 0 1 2 3 4 5 6 [ ] [ ] ... ... [ ] ... [ ] [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] Picosecond 2: 0 1 2 3 4 5 6 [ ] [S] ... ... [ ] ... [ ] [ ] [ ] [ ] [ ] [S] [S] [S] [ ] [ ] Picosecond 3: 0 1 2 3 4 5 6 [ ] [ ] ... ... [ ] ... [ ] [S] [S] [ ] [ ] [ ] [ ] [ ] [S] [S] Your plan is to hitch a ride on a packet about to move through the firewall. The packet will travel along the top of each layer, and it moves at one layer per picosecond. Each picosecond, the packet moves one layer forward (its first move takes it into layer 0), and then the scanners move one step. If there is a scanner at the top of the layer as your packet enters it, you are caught. (If a scanner moves into the top of its layer while you are there, you are not caught: it doesn't have time to notice you before you leave.) If you were to do this in the configuration above, marking your current position with parentheses, your passage through the firewall would look like this: Initial state: 0 1 2 3 4 5 6 [S] [S] ... ... [S] ... [S] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] Picosecond 0: 0 1 2 3 4 5 6 (S) [S] ... ... [S] ... [S] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] 0 1 2 3 4 5 6 ( ) [ ] ... ... [ ] ... [ ] [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] Picosecond 1: 0 1 2 3 4 5 6 [ ] ( ) ... ... [ ] ... [ ] [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] 0 1 2 3 4 5 6 [ ] (S) ... ... [ ] ... [ ] [ ] [ ] [ ] [ ] [S] [S] [S] [ ] [ ] Picosecond 2: 0 1 2 3 4 5 6 [ ] [S] (.) ... [ ] ... [ ] [ ] [ ] [ ] [ ] [S] [S] [S] [ ] [ ] 0 1 2 3 4 5 6 [ ] [ ] (.) ... [ ] ... [ ] [S] [S] [ ] [ ] [ ] [ ] [ ] [S] [S] Picosecond 3: 0 1 2 3 4 5 6 [ ] [ ] ... (.) [ ] ... [ ] [S] [S] [ ] [ ] [ ] [ ] [ ] [S] [S] 0 1 2 3 4 5 6 [S] [S] ... (.) [ ] ... [ ] [ ] [ ] [ ] [ ] [ ] [S] [S] [ ] [ ] Picosecond 4: 0 1 2 3 4 5 6 [S] [S] ... ... ( ) ... [ ] [ ] [ ] [ ] [ ] [ ] [S] [S] [ ] [ ] 0 1 2 3 4 5 6 [ ] [ ] ... ... ( ) ... [ ] [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] Picosecond 5: 0 1 2 3 4 5 6 [ ] [ ] ... ... [ ] (.) [ ] [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] 0 1 2 3 4 5 6 [ ] [S] ... ... [S] (.) [S] [ ] [ ] [ ] [ ] [S] [ ] [ ] [ ] [ ] Picosecond 6: 0 1 2 3 4 5 6 [ ] [S] ... ... [S] ... (S) [ ] [ ] [ ] [ ] [S] [ ] [ ] [ ] [ ] 0 1 2 3 4 5 6 [ ] [ ] ... ... [ ] ... ( ) [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] In this situation, you are caught in layers 0 and 6, because your packet entered the layer when its scanner was at the top when you entered it. You are not caught in layer 1, since the scanner moved into the top of the layer once you were already there. The severity of getting caught on a layer is equal to its depth multiplied by its range. (Ignore layers in which you do not get caught.) The severity of the whole trip is the sum of these values. In the example above, the trip severity is 0*3 + 6*4 = 24. Given the details of the firewall you've recorded, if you leave immediately, what is the severity of your whole trip? Your puzzle answer was 1960. --- Part Two --- Now, you need to pass through the firewall without being caught - easier said than done. You can't control the speed of the packet, but you can delay it any number of picoseconds. For each picosecond you delay the packet before beginning your trip, all security scanners move one step. You're not in the firewall during this time; you don't enter layer 0 until you stop delaying the packet. In the example above, if you delay 10 picoseconds (picoseconds 0 - 9), you won't get caught: State after delaying: 0 1 2 3 4 5 6 [ ] [S] ... ... [ ] ... [ ] [ ] [ ] [ ] [ ] [S] [S] [S] [ ] [ ] Picosecond 10: 0 1 2 3 4 5 6 ( ) [S] ... ... [ ] ... [ ] [ ] [ ] [ ] [ ] [S] [S] [S] [ ] [ ] 0 1 2 3 4 5 6 ( ) [ ] ... ... [ ] ... [ ] [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] Picosecond 11: 0 1 2 3 4 5 6 [ ] ( ) ... ... [ ] ... [ ] [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] 0 1 2 3 4 5 6 [S] (S) ... ... [S] ... [S] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] Picosecond 12: 0 1 2 3 4 5 6 [S] [S] (.) ... [S] ... [S] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] [ ] 0 1 2 3 4 5 6 [ ] [ ] (.) ... [ ] ... [ ] [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] Picosecond 13: 0 1 2 3 4 5 6 [ ] [ ] ... (.) [ ] ... [ ] [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] 0 1 2 3 4 5 6 [ ] [S] ... (.) [ ] ... [ ] [ ] [ ] [ ] [ ] [S] [S] [S] [ ] [ ] Picosecond 14: 0 1 2 3 4 5 6 [ ] [S] ... ... ( ) ... [ ] [ ] [ ] [ ] [ ] [S] [S] [S] [ ] [ ] 0 1 2 3 4 5 6 [ ] [ ] ... ... ( ) ... [ ] [S] [S] [ ] [ ] [ ] [ ] [ ] [S] [S] Picosecond 15: 0 1 2 3 4 5 6 [ ] [ ] ... ... [ ] (.) [ ] [S] [S] [ ] [ ] [ ] [ ] [ ] [S] [S] 0 1 2 3 4 5 6 [S] [S] ... ... [ ] (.) [ ] [ ] [ ] [ ] [ ] [ ] [S] [S] [ ] [ ] Picosecond 16: 0 1 2 3 4 5 6 [S] [S] ... ... [ ] ... ( ) [ ] [ ] [ ] [ ] [ ] [S] [S] [ ] [ ] 0 1 2 3 4 5 6 [ ] [ ] ... ... [ ] ... ( ) [S] [S] [S] [S] [ ] [ ] [ ] [ ] [ ] Because all smaller delays would get you caught, the fewest number of picoseconds you would need to delay to get through safely is 10. What is the fewest number of picoseconds that you need to delay the packet to pass through the firewall without being caught?
299