Supa-AI commited on
Commit
73ea81d
·
verified ·
1 Parent(s): 1a8db0d

Upload aoc.csv

Browse files
Files changed (1) hide show
  1. aoc.csv +1615 -295
aoc.csv CHANGED
@@ -16102,8 +16102,7 @@ def simulate_motion(positions, velocities, num_x=101, num_y=103, steps=10000):
16102
 
16103
  if __name__ == ""__main__"":
16104
  positions, velocities = read_input(""input.txt"")
16105
- simulate_motion(positions, velocities)
16106
- ",python:3.9.21-slim
16107
  2024,14,2,"--- Day 14: Restroom Redoubt ---
16108
 
16109
  One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters.
@@ -16393,8 +16392,7 @@ for T in range(R*C):
16393
  while '#'*t in S: t += 1
16394
  if t > B[0]: B = (t, T)
16395
  if T == 100: print('Part 1:', Z[0]*Z[1]*Z[2]*Z[3])
16396
- print('Part 2:', B[1])
16397
- ",python:3.9.21-slim
16398
  2024,14,2,"--- Day 14: Restroom Redoubt ---
16399
 
16400
  One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters.
@@ -16587,8 +16585,7 @@ print(""at second: "", found_at_second)
16587
  # O(WIDE * TALL * n) so kindof O(n) :)
16588
 
16589
  # Total space complexity
16590
- # O(WIDE * TALL + n) so kindof O(n) :)
16591
- ",python:3.9.21-slim
16592
  2024,14,2,"--- Day 14: Restroom Redoubt ---
16593
 
16594
  One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters.
@@ -16768,9 +16765,7 @@ for i in range(1, 100000):
16768
  #the tree picture has 31 robots in a single row
16769
  if max_sum > 30:
16770
  print(i)
16771
- break
16772
-
16773
- ",python:3.9.21-slim
16774
  2024,15,1,"--- Day 15: Warehouse Woes ---
16775
 
16776
  You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well?
@@ -27627,12 +27622,161 @@ The keypads form a chain, just like before: your directional keypad controls a r
27627
 
27628
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
27629
 
27630
- Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"from part1 import parse_input, solve
 
 
27631
 
27632
- if __name__ == ""__main__"":
27633
- input_data = parse_input('input.txt')
27634
- result = sum(solve(sequence, 0, 25) * multiplier for sequence, multiplier in input_data)
27635
- print(result)",python:3.9.21-slim
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27636
  2024,21,2,"--- Day 21: Keypad Conundrum ---
27637
 
27638
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
@@ -51732,210 +51876,209 @@ for (let i = 1; i < 100000; i++) {
51732
  console.log(""Tree appears at second:"", i);
51733
  break;
51734
  }
51735
- }
51736
- ",node:14
51737
- 2024,14,2,"--- Day 14: Restroom Redoubt ---
51738
-
51739
- One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters.
51740
-
51741
- Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots!
51742
-
51743
- To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines.
51744
-
51745
- You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example:
51746
-
51747
- p=0,4 v=3,-3
51748
- p=6,3 v=-1,-3
51749
- p=10,3 v=-1,2
51750
- p=2,0 v=2,-1
51751
- p=0,0 v=1,3
51752
- p=3,0 v=-2,-2
51753
- p=7,6 v=-1,-3
51754
- p=3,0 v=-1,-2
51755
- p=9,3 v=2,3
51756
- p=7,3 v=-1,2
51757
- p=2,4 v=2,-3
51758
- p=9,5 v=-3,-3
51759
- Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner.
51760
-
51761
- Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up.
51762
-
51763
- The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall.
51764
-
51765
- The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this:
51766
-
51767
- 1.12.......
51768
- ...........
51769
- ...........
51770
- ......11.11
51771
- 1.1........
51772
- .........1.
51773
- .......1...
51774
- These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds:
51775
-
51776
- Initial state:
51777
- ...........
51778
- ...........
51779
- ...........
51780
- ...........
51781
- ..1........
51782
- ...........
51783
- ...........
51784
-
51785
- After 1 second:
51786
- ...........
51787
- ....1......
51788
- ...........
51789
- ...........
51790
- ...........
51791
- ...........
51792
- ...........
51793
-
51794
- After 2 seconds:
51795
- ...........
51796
- ...........
51797
- ...........
51798
- ...........
51799
- ...........
51800
- ......1....
51801
- ...........
51802
-
51803
- After 3 seconds:
51804
- ...........
51805
- ...........
51806
- ........1..
51807
- ...........
51808
- ...........
51809
- ...........
51810
- ...........
51811
-
51812
- After 4 seconds:
51813
- ...........
51814
- ...........
51815
- ...........
51816
- ...........
51817
- ...........
51818
- ...........
51819
- ..........1
51820
-
51821
- After 5 seconds:
51822
- ...........
51823
- ...........
51824
- ...........
51825
- .1.........
51826
- ...........
51827
- ...........
51828
- ...........
51829
- The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds?
51830
-
51831
- In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this:
51832
-
51833
- ......2..1.
51834
- ...........
51835
- 1..........
51836
- .11........
51837
- .....1.....
51838
- ...12......
51839
- .1....1....
51840
- To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are:
51841
-
51842
- ..... 2..1.
51843
- ..... .....
51844
- 1.... .....
51845
-
51846
- ..... .....
51847
- ...12 .....
51848
- .1... 1....
51849
- In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12.
51850
-
51851
- Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?
51852
-
51853
- Your puzzle answer was 219150360.
51854
-
51855
- --- Part Two ---
51856
-
51857
- During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree.
51858
-
51859
- What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import { readFileSync } from 'node:fs';
51860
-
51861
- // Constants
51862
- const WIDTH = 101;
51863
- const HEIGHT = 103;
51864
- const SECONDS = 100;
51865
-
51866
- // Read input data
51867
- const inputData = readFileSync('input.txt', { encoding: 'utf8', flag: 'r' });
51868
-
51869
- // Robot class definition
51870
- class Robot {
51871
- constructor(initialState) {
51872
- const { px, py, vx, vy } = /p=(?<px>-{0,1}\d+),(?<py>-{0,1}\d+) v=(?<vx>-{0,1}\d+),(?<vy>-{0,1}\d+)/.exec(initialState).groups;
51873
- this.position = { x: parseInt(px), y: parseInt(py) };
51874
- this.velocity = { x: parseInt(vx), y: parseInt(vy) };
51875
- }
51876
-
51877
- move() {
51878
- this.position.x = (this.position.x + this.velocity.x + WIDTH) % WIDTH;
51879
- this.position.y = (this.position.y + this.velocity.y + HEIGHT) % HEIGHT;
51880
- }
51881
-
51882
- isWithinBounds(topLeft, bottomRight) {
51883
- return (
51884
- topLeft.x <= this.position.x && this.position.x < bottomRight.x &&
51885
- topLeft.y <= this.position.y && this.position.y < bottomRight.y
51886
- );
51887
- }
51888
- }
51889
-
51890
- // Parse input and initialize robots
51891
- const robots = inputData
51892
- .split('\n')
51893
- .filter(line => line.trim())
51894
- .map(line => new Robot(line));
51895
-
51896
- // Simulate robot movements for the initial period
51897
- for (let i = 0; i < SECONDS; i++) {
51898
- robots.forEach(robot => robot.move());
51899
- }
51900
-
51901
- // Calculate quadrant counts
51902
- const quadrants = [
51903
- { topLeft: { x: 0, y: 0 }, bottomRight: { x: Math.floor(WIDTH / 2), y: Math.floor(HEIGHT / 2) } },
51904
- { topLeft: { x: Math.ceil(WIDTH / 2), y: 0 }, bottomRight: { x: WIDTH, y: Math.floor(HEIGHT / 2) } },
51905
- { topLeft: { x: 0, y: Math.ceil(HEIGHT / 2) }, bottomRight: { x: Math.floor(WIDTH / 2), y: HEIGHT } },
51906
- { topLeft: { x: Math.ceil(WIDTH / 2), y: Math.ceil(HEIGHT / 2) }, bottomRight: { x: WIDTH, y: HEIGHT } }
51907
- ];
51908
-
51909
- const quadrantCounts = quadrants.map(({ topLeft, bottomRight }) =>
51910
- robots.reduce((count, robot) => robot.isWithinBounds(topLeft, bottomRight) ? count + 1 : count, 0)
51911
- );
51912
-
51913
- console.log(quadrantCounts.reduce((product, count) => product * count, 1));
51914
-
51915
- // Extended simulation to find a stable pattern
51916
- for (let i = SECONDS; i < 19000; i++) {
51917
- const grid = Array.from({ length: HEIGHT }, () => Array(WIDTH).fill('.'));
51918
- let robotsInCentralArea = 0;
51919
-
51920
- robots.forEach(robot => {
51921
- const { x, y } = robot.position;
51922
- grid[y][x] = '#';
51923
-
51924
- if (robot.isWithinBounds(
51925
- { x: Math.floor(WIDTH * 0.25), y: Math.floor(HEIGHT * 0.25) },
51926
- { x: Math.floor(WIDTH * 0.75), y: Math.floor(HEIGHT * 0.75) }
51927
- )) {
51928
- robotsInCentralArea++;
51929
- }
51930
-
51931
- robot.move();
51932
- });
51933
-
51934
- if (robotsInCentralArea >= Math.floor(robots.length / 2)) {
51935
- console.log(i);
51936
- grid.forEach(row => console.log(row.join('')));
51937
- break;
51938
- }
51939
  }",node:14
51940
  2024,14,2,"--- Day 14: Restroom Redoubt ---
51941
 
@@ -52322,8 +52465,7 @@ for (let counter = 0; counter < 10000; counter++) {
52322
  }
52323
 
52324
  initialPositions = newInitialPositions;
52325
- }
52326
- ",node:14
52327
  2024,16,1,"--- Day 16: Reindeer Maze ---
52328
 
52329
  It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score.
@@ -70052,94 +70194,96 @@ The length of the shortest sequence of button presses you need to type on your d
70052
  The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29.
70053
  In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384.
70054
 
70055
- Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,,node:14
70056
- 2024,21,1,"--- Day 21: Keypad Conundrum ---
70057
-
70058
- As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
70059
-
70060
- The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door.
70061
-
70062
- The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this:
70063
-
70064
- +---+---+---+
70065
- | 7 | 8 | 9 |
70066
- +---+---+---+
70067
- | 4 | 5 | 6 |
70068
- +---+---+---+
70069
- | 1 | 2 | 3 |
70070
- +---+---+---+
70071
- | 0 | A |
70072
- +---+---+
70073
- Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead.
70074
-
70075
- The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad.
70076
-
70077
- The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this:
70078
 
70079
- +---+---+
70080
- | ^ | A |
70081
- +---+---+---+
70082
- | < | v | > |
70083
- +---+---+---+
70084
- When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm.
 
 
70085
 
70086
- For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is:
 
 
 
 
 
70087
 
70088
- < to move the arm from A (its initial position) to 0.
70089
- A to push the 0 button.
70090
- ^A to move the arm to the 2 button and push it.
70091
- >^^A to move the arm to the 9 button and push it.
70092
- vvvA to move the arm to the A button and push it.
70093
- In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA.
70094
 
70095
- Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead.
 
 
 
 
70096
 
70097
- When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad).
70098
 
70099
- There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A.
 
 
 
70100
 
70101
- Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too.
 
 
 
70102
 
70103
- There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A.
 
 
 
70104
 
70105
- Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself.
 
 
 
70106
 
70107
- Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad:
 
 
70108
 
70109
- <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A
70110
- v<<A>>^A<A>AvA<^AA>A<vAAA>^A
70111
- <A^A>^^AvvvA
70112
- 029A
70113
- In summary, there are the following keypads:
70114
 
70115
- One directional keypad that you are using.
70116
- Two directional keypads that robots are using.
70117
- One numeric keypad (on a door) that a robot is using.
70118
- It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is.
70119
 
70120
- To unlock the door, five codes will need to be typed on its numeric keypad. For example:
 
70121
 
70122
- 029A
70123
- 980A
70124
- 179A
70125
- 456A
70126
- 379A
70127
- For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad:
70128
 
70129
- 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A
70130
- 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A
70131
- 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A
70132
- 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A
70133
- 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A
70134
- The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary.
70135
 
70136
- The complexity of a single code (like 029A) is equal to the result of multiplying these two values:
 
 
70137
 
70138
- The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68.
70139
- The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29.
70140
- In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384.
70141
 
70142
- Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,,node:14
70143
  2024,21,1,"--- Day 21: Keypad Conundrum ---
70144
 
70145
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
@@ -70226,7 +70370,511 @@ The length of the shortest sequence of button presses you need to type on your d
70226
  The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29.
70227
  In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384.
70228
 
70229
- Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,,node:14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70230
  2024,21,1,"--- Day 21: Keypad Conundrum ---
70231
 
70232
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
@@ -70887,7 +71535,310 @@ The keypads form a chain, just like before: your directional keypad controls a r
70887
 
70888
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
70889
 
70890
- Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,,node:14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70891
  2024,21,2,"--- Day 21: Keypad Conundrum ---
70892
 
70893
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
@@ -70993,7 +71944,101 @@ The keypads form a chain, just like before: your directional keypad controls a r
70993
 
70994
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
70995
 
70996
- Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,,node:14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70997
  2024,21,2,"--- Day 21: Keypad Conundrum ---
70998
 
70999
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
@@ -71099,7 +72144,100 @@ The keypads form a chain, just like before: your directional keypad controls a r
71099
 
71100
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
71101
 
71102
- Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,,node:14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71103
  2024,21,2,"--- Day 21: Keypad Conundrum ---
71104
 
71105
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
@@ -71205,7 +72343,189 @@ The keypads form a chain, just like before: your directional keypad controls a r
71205
 
71206
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
71207
 
71208
- Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,,node:14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71209
  2024,22,1,"--- Day 22: Monkey Market ---
71210
 
71211
  As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.
 
16102
 
16103
  if __name__ == ""__main__"":
16104
  positions, velocities = read_input(""input.txt"")
16105
+ simulate_motion(positions, velocities)",python:3.9.21-slim
 
16106
  2024,14,2,"--- Day 14: Restroom Redoubt ---
16107
 
16108
  One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters.
 
16392
  while '#'*t in S: t += 1
16393
  if t > B[0]: B = (t, T)
16394
  if T == 100: print('Part 1:', Z[0]*Z[1]*Z[2]*Z[3])
16395
+ print('Part 2:', B[1])",python:3.9.21-slim
 
16396
  2024,14,2,"--- Day 14: Restroom Redoubt ---
16397
 
16398
  One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters.
 
16585
  # O(WIDE * TALL * n) so kindof O(n) :)
16586
 
16587
  # Total space complexity
16588
+ # O(WIDE * TALL + n) so kindof O(n) :)",python:3.9.21-slim
 
16589
  2024,14,2,"--- Day 14: Restroom Redoubt ---
16590
 
16591
  One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters.
 
16765
  #the tree picture has 31 robots in a single row
16766
  if max_sum > 30:
16767
  print(i)
16768
+ break",python:3.9.21-slim
 
 
16769
  2024,15,1,"--- Day 15: Warehouse Woes ---
16770
 
16771
  You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well?
 
27622
 
27623
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
27624
 
27625
+ Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"import sys
27626
+ from collections import Counter
27627
+ from functools import cache
27628
 
27629
+
27630
+ def test_input():
27631
+ _input = """"""029A
27632
+ 980A
27633
+ 179A
27634
+ 456A
27635
+ 379A"""""".strip().split('\n')
27636
+
27637
+ assert part_1(_input) == 126384
27638
+
27639
+
27640
+ class Pad:
27641
+ LOOKUPS = {}
27642
+
27643
+ def inputs(self, sequence: str):
27644
+ inputs = []
27645
+
27646
+ def _inputs(result, current, sequence):
27647
+ if len(sequence) == 0:
27648
+ inputs.append(result)
27649
+ return
27650
+ for move in self._inputs(current, sequence[0]):
27651
+ _inputs(result + move, sequence[0], sequence[1:])
27652
+
27653
+ _inputs('', 'A', sequence)
27654
+
27655
+ return inputs
27656
+
27657
+ def _inputs(self, start: str, end: str):
27658
+ sx, sy = self.LOOKUPS[start]
27659
+ ex, ey = self.LOOKUPS[end]
27660
+ dx, dy = ex - sx, ey - sy
27661
+
27662
+ x_str = '<' * -dx if dx < 0 else '>' * dx
27663
+ y_str = '^' * -dy if dy < 0 else 'v' * dy
27664
+
27665
+ value = []
27666
+ if dy != 0 and (sx, sy + dy) != self.LOOKUPS[' ']:
27667
+ value.append(f'{y_str}{x_str}A')
27668
+ if dx != 0 and (sx + dx, sy) != self.LOOKUPS[' ']:
27669
+ value.append(f'{x_str}{y_str}A')
27670
+ if dx == dy == 0:
27671
+ value.append('A')
27672
+
27673
+ return value
27674
+
27675
+
27676
+ class Numpad(Pad):
27677
+ """"""
27678
+ A class representing a numpad with a specific layout.
27679
+
27680
+ The numpad layout is as follows:
27681
+ +---+---+---+
27682
+ | 7 | 8 | 9 |
27683
+ +---+---+---+
27684
+ | 4 | 5 | 6 |
27685
+ +---+---+---+
27686
+ | 1 | 2 | 3 |
27687
+ +---+---+---+
27688
+ | 0 | A |
27689
+ +---+---+
27690
+
27691
+ Attributes:
27692
+ LOOKUPS (dict): A dictionary containing lookup values for the numpad.
27693
+ """"""
27694
+
27695
+ LOOKUPS = {
27696
+ '7': (0, 0),
27697
+ '8': (1, 0),
27698
+ '9': (2, 0),
27699
+ '4': (0, 1),
27700
+ '5': (1, 1),
27701
+ '6': (2, 1),
27702
+ '1': (0, 2),
27703
+ '2': (1, 2),
27704
+ '3': (2, 2),
27705
+ ' ': (0, 3),
27706
+ '0': (1, 3),
27707
+ 'A': (2, 3),
27708
+ }
27709
+
27710
+
27711
+ class Dirpad(Pad):
27712
+ """"""
27713
+ A class representing a direction pad with a specific layout.
27714
+
27715
+ The direction pad layout is as follows:
27716
+ +---+---+
27717
+ | ^ | A |
27718
+ +---+---+---+
27719
+ | < | v | > |
27720
+ +---+---+---+
27721
+
27722
+ Attributes:
27723
+ LOOKUPS (dict): A dictionary containing lookup values for the direction pad.
27724
+ """"""
27725
+
27726
+ LOOKUPS = {
27727
+ ' ': (0, 0),
27728
+ '^': (1, 0),
27729
+ 'A': (2, 0),
27730
+ '<': (0, 1),
27731
+ 'v': (1, 1),
27732
+ '>': (2, 1),
27733
+ }
27734
+
27735
+
27736
+ def read_input(path: str) -> list[str]:
27737
+ with open(path) as input_file:
27738
+ return [line.strip() for line in input_file]
27739
+
27740
+
27741
+ @cache
27742
+ def shortest(sequence: str, depth: int):
27743
+ dirpad = Dirpad()
27744
+ if depth == 0:
27745
+ return len(sequence)
27746
+
27747
+ total = 0
27748
+ for sub in sequence.split('A')[:-1]:
27749
+ sequences = dirpad.inputs(sub + 'A')
27750
+ total += min(shortest(seq, depth - 1) for seq in sequences)
27751
+ return total
27752
+
27753
+
27754
+ def score_at_depth(input_data: list[str], depth: int) -> int:
27755
+ total = 0
27756
+ numpad = Numpad()
27757
+ for code in input_data:
27758
+ numcode = numpad.inputs(code)
27759
+ min_len = min(shortest(nc, depth) for nc in numcode)
27760
+ total += min_len * int(code[:-1])
27761
+ return total
27762
+
27763
+
27764
+ def part_1(input_data: list[str]) -> int:
27765
+ return score_at_depth(input_data, 2)
27766
+
27767
+
27768
+ def part_2(input_data: list[str]) -> int:
27769
+ return score_at_depth(input_data, 25)
27770
+
27771
+
27772
+ def main():
27773
+ input_data = read_input(sys.argv[1])
27774
+ print(f'Part 1: {part_1(input_data)}')
27775
+ print(f'Part 2: {part_2(input_data)}')
27776
+
27777
+
27778
+ if __name__ == '__main__':
27779
+ main()",python:3.9.21-slim
27780
  2024,21,2,"--- Day 21: Keypad Conundrum ---
27781
 
27782
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
 
51876
  console.log(""Tree appears at second:"", i);
51877
  break;
51878
  }
51879
+ }",node:14
51880
+ 2024,14,2,"--- Day 14: Restroom Redoubt ---
51881
+
51882
+ One of The Historians needs to use the bathroom; fortunately, you know there's a bathroom near an unvisited location on their list, and so you're all quickly teleported directly to the lobby of Easter Bunny Headquarters.
51883
+
51884
+ Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots!
51885
+
51886
+ To get The Historian safely to the bathroom, you'll need a way to predict where the robots will be in the future. Fortunately, they all seem to be moving on the tile floor in predictable straight lines.
51887
+
51888
+ You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example:
51889
+
51890
+ p=0,4 v=3,-3
51891
+ p=6,3 v=-1,-3
51892
+ p=10,3 v=-1,2
51893
+ p=2,0 v=2,-1
51894
+ p=0,0 v=1,3
51895
+ p=3,0 v=-2,-2
51896
+ p=7,6 v=-1,-3
51897
+ p=3,0 v=-1,-2
51898
+ p=9,3 v=2,3
51899
+ p=7,3 v=-1,2
51900
+ p=2,4 v=2,-3
51901
+ p=9,5 v=-3,-3
51902
+ Each robot's position is given as p=x,y where x represents the number of tiles the robot is from the left wall and y represents the number of tiles from the top wall (when viewed from above). So, a position of p=0,0 means the robot is all the way in the top-left corner.
51903
+
51904
+ Each robot's velocity is given as v=x,y where x and y are given in tiles per second. Positive x means the robot is moving to the right, and positive y means the robot is moving down. So, a velocity of v=1,-2 means that each second, the robot moves 1 tile to the right and 2 tiles up.
51905
+
51906
+ The robots outside the actual bathroom are in a space which is 101 tiles wide and 103 tiles tall (when viewed from above). However, in this example, the robots are in a space which is only 11 tiles wide and 7 tiles tall.
51907
+
51908
+ The robots are good at navigating over/under each other (due to a combination of springs, extendable legs, and quadcopters), so they can share the same tile and don't interact with each other. Visually, the number of robots on each tile in this example looks like this:
51909
+
51910
+ 1.12.......
51911
+ ...........
51912
+ ...........
51913
+ ......11.11
51914
+ 1.1........
51915
+ .........1.
51916
+ .......1...
51917
+ These robots have a unique feature for maximum bathroom security: they can teleport. When a robot would run into an edge of the space they're in, they instead teleport to the other side, effectively wrapping around the edges. Here is what robot p=2,4 v=2,-3 does for the first few seconds:
51918
+
51919
+ Initial state:
51920
+ ...........
51921
+ ...........
51922
+ ...........
51923
+ ...........
51924
+ ..1........
51925
+ ...........
51926
+ ...........
51927
+
51928
+ After 1 second:
51929
+ ...........
51930
+ ....1......
51931
+ ...........
51932
+ ...........
51933
+ ...........
51934
+ ...........
51935
+ ...........
51936
+
51937
+ After 2 seconds:
51938
+ ...........
51939
+ ...........
51940
+ ...........
51941
+ ...........
51942
+ ...........
51943
+ ......1....
51944
+ ...........
51945
+
51946
+ After 3 seconds:
51947
+ ...........
51948
+ ...........
51949
+ ........1..
51950
+ ...........
51951
+ ...........
51952
+ ...........
51953
+ ...........
51954
+
51955
+ After 4 seconds:
51956
+ ...........
51957
+ ...........
51958
+ ...........
51959
+ ...........
51960
+ ...........
51961
+ ...........
51962
+ ..........1
51963
+
51964
+ After 5 seconds:
51965
+ ...........
51966
+ ...........
51967
+ ...........
51968
+ .1.........
51969
+ ...........
51970
+ ...........
51971
+ ...........
51972
+ The Historian can't wait much longer, so you don't have to simulate the robots for very long. Where will the robots be after 100 seconds?
51973
+
51974
+ In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this:
51975
+
51976
+ ......2..1.
51977
+ ...........
51978
+ 1..........
51979
+ .11........
51980
+ .....1.....
51981
+ ...12......
51982
+ .1....1....
51983
+ To determine the safest area, count the number of robots in each quadrant after 100 seconds. Robots that are exactly in the middle (horizontally or vertically) don't count as being in any quadrant, so the only relevant robots are:
51984
+
51985
+ ..... 2..1.
51986
+ ..... .....
51987
+ 1.... .....
51988
+
51989
+ ..... .....
51990
+ ...12 .....
51991
+ .1... 1....
51992
+ In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12.
51993
+
51994
+ Predict the motion of the robots in your list within a space which is 101 tiles wide and 103 tiles tall. What will the safety factor be after exactly 100 seconds have elapsed?
51995
+
51996
+ Your puzzle answer was 219150360.
51997
+
51998
+ --- Part Two ---
51999
+
52000
+ During the bathroom break, someone notices that these robots seem awfully similar to ones built and used at the North Pole. If they're the same type of robots, they should have a hard-coded Easter egg: very rarely, most of the robots should arrange themselves into a picture of a Christmas tree.
52001
+
52002
+ What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import { readFileSync } from 'node:fs';
52003
+
52004
+ // Constants
52005
+ const WIDTH = 101;
52006
+ const HEIGHT = 103;
52007
+ const SECONDS = 100;
52008
+
52009
+ // Read input data
52010
+ const inputData = readFileSync('input.txt', { encoding: 'utf8', flag: 'r' });
52011
+
52012
+ // Robot class definition
52013
+ class Robot {
52014
+ constructor(initialState) {
52015
+ const { px, py, vx, vy } = /p=(?<px>-{0,1}\d+),(?<py>-{0,1}\d+) v=(?<vx>-{0,1}\d+),(?<vy>-{0,1}\d+)/.exec(initialState).groups;
52016
+ this.position = { x: parseInt(px), y: parseInt(py) };
52017
+ this.velocity = { x: parseInt(vx), y: parseInt(vy) };
52018
+ }
52019
+
52020
+ move() {
52021
+ this.position.x = (this.position.x + this.velocity.x + WIDTH) % WIDTH;
52022
+ this.position.y = (this.position.y + this.velocity.y + HEIGHT) % HEIGHT;
52023
+ }
52024
+
52025
+ isWithinBounds(topLeft, bottomRight) {
52026
+ return (
52027
+ topLeft.x <= this.position.x && this.position.x < bottomRight.x &&
52028
+ topLeft.y <= this.position.y && this.position.y < bottomRight.y
52029
+ );
52030
+ }
52031
+ }
52032
+
52033
+ // Parse input and initialize robots
52034
+ const robots = inputData
52035
+ .split('\n')
52036
+ .filter(line => line.trim())
52037
+ .map(line => new Robot(line));
52038
+
52039
+ // Simulate robot movements for the initial period
52040
+ for (let i = 0; i < SECONDS; i++) {
52041
+ robots.forEach(robot => robot.move());
52042
+ }
52043
+
52044
+ // Calculate quadrant counts
52045
+ const quadrants = [
52046
+ { topLeft: { x: 0, y: 0 }, bottomRight: { x: Math.floor(WIDTH / 2), y: Math.floor(HEIGHT / 2) } },
52047
+ { topLeft: { x: Math.ceil(WIDTH / 2), y: 0 }, bottomRight: { x: WIDTH, y: Math.floor(HEIGHT / 2) } },
52048
+ { topLeft: { x: 0, y: Math.ceil(HEIGHT / 2) }, bottomRight: { x: Math.floor(WIDTH / 2), y: HEIGHT } },
52049
+ { topLeft: { x: Math.ceil(WIDTH / 2), y: Math.ceil(HEIGHT / 2) }, bottomRight: { x: WIDTH, y: HEIGHT } }
52050
+ ];
52051
+
52052
+ const quadrantCounts = quadrants.map(({ topLeft, bottomRight }) =>
52053
+ robots.reduce((count, robot) => robot.isWithinBounds(topLeft, bottomRight) ? count + 1 : count, 0)
52054
+ );
52055
+
52056
+ console.log(quadrantCounts.reduce((product, count) => product * count, 1));
52057
+
52058
+ // Extended simulation to find a stable pattern
52059
+ for (let i = SECONDS; i < 19000; i++) {
52060
+ const grid = Array.from({ length: HEIGHT }, () => Array(WIDTH).fill('.'));
52061
+ let robotsInCentralArea = 0;
52062
+
52063
+ robots.forEach(robot => {
52064
+ const { x, y } = robot.position;
52065
+ grid[y][x] = '#';
52066
+
52067
+ if (robot.isWithinBounds(
52068
+ { x: Math.floor(WIDTH * 0.25), y: Math.floor(HEIGHT * 0.25) },
52069
+ { x: Math.floor(WIDTH * 0.75), y: Math.floor(HEIGHT * 0.75) }
52070
+ )) {
52071
+ robotsInCentralArea++;
52072
+ }
52073
+
52074
+ robot.move();
52075
+ });
52076
+
52077
+ if (robotsInCentralArea >= Math.floor(robots.length / 2)) {
52078
+ console.log(i);
52079
+ grid.forEach(row => console.log(row.join('')));
52080
+ break;
52081
+ }
 
52082
  }",node:14
52083
  2024,14,2,"--- Day 14: Restroom Redoubt ---
52084
 
 
52465
  }
52466
 
52467
  initialPositions = newInitialPositions;
52468
+ }",node:14
 
52469
  2024,16,1,"--- Day 16: Reindeer Maze ---
52470
 
52471
  It's time again for the Reindeer Olympics! This year, the big event is the Reindeer Maze, where the Reindeer compete for the lowest score.
 
70194
  The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29.
70195
  In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384.
70196
 
70197
+ Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"const fs = require(""fs"");
70198
+
70199
+ const NUMS = {
70200
+ ""0"": [3, 1],
70201
+ ""1"": [2, 0],
70202
+ ""2"": [2, 1],
70203
+ ""3"": [2, 2],
70204
+ ""4"": [1, 0],
70205
+ ""5"": [1, 1],
70206
+ ""6"": [1, 2],
70207
+ ""7"": [0, 0],
70208
+ ""8"": [0, 1],
70209
+ ""9"": [0, 2],
70210
+ ""A"": [3, 2],
70211
+ """": [3, 0],
70212
+ };
 
 
 
 
 
 
 
70213
 
70214
+ const ARROWS = {
70215
+ ""^"": [0, 1],
70216
+ ""A"": [0, 2],
70217
+ ""<"": [1, 0],
70218
+ ""v"": [1, 1],
70219
+ "">"": [1, 2],
70220
+ """": [0, 0],
70221
+ };
70222
 
70223
+ const DIR_TO_ARROW_MAP = {
70224
+ ""-1,0"": ""^"",
70225
+ ""1,0"": ""v"",
70226
+ ""0,-1"": ""<"",
70227
+ ""0,1"": "">"",
70228
+ };
70229
 
70230
+ function getShortest(keys, sequence) {
70231
+ let path = [];
 
 
 
 
70232
 
70233
+ for (let i = 0; i < sequence.length - 1; i++) {
70234
+ let cur = keys[sequence[i]];
70235
+ let target = keys[sequence[i + 1]];
70236
+ let nextPath = [];
70237
+ let dirs = [];
70238
 
70239
+ if (!cur || !target) continue;
70240
 
70241
+ for (let y = cur[1] - 1; y >= target[1]; y--) {
70242
+ nextPath.push([cur[0], y]);
70243
+ dirs.push([0, -1]);
70244
+ }
70245
 
70246
+ for (let x = cur[0] + 1; x <= target[0]; x++) {
70247
+ nextPath.push([x, cur[1]]);
70248
+ dirs.push([1, 0]);
70249
+ }
70250
 
70251
+ for (let x = cur[0] - 1; x >= target[0]; x--) {
70252
+ nextPath.push([x, cur[1]]);
70253
+ dirs.push([-1, 0]);
70254
+ }
70255
 
70256
+ for (let y = cur[1] + 1; y <= target[1]; y++) {
70257
+ nextPath.push([cur[0], y]);
70258
+ dirs.push([0, 1]);
70259
+ }
70260
 
70261
+ if (nextPath.some((pos) => JSON.stringify(pos) === JSON.stringify(keys[""""]))) {
70262
+ dirs.reverse();
70263
+ }
70264
 
70265
+ path.push(...dirs.map((d) => DIR_TO_ARROW_MAP[d.join("","")]), ""A"");
70266
+ }
 
 
 
70267
 
70268
+ return path.join("""");
70269
+ }
 
 
70270
 
70271
+ // Read input file
70272
+ const lines = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n"");
70273
 
70274
+ let totalComplexity = 0;
 
 
 
 
 
70275
 
70276
+ for (let line of lines) {
70277
+ if (!line) continue;
 
 
 
 
70278
 
70279
+ let l1 = getShortest(NUMS, ""A"" + line);
70280
+ let l2 = getShortest(ARROWS, ""A"" + l1);
70281
+ let l3 = getShortest(ARROWS, ""A"" + l2);
70282
 
70283
+ totalComplexity += parseInt(line.slice(0, -1)) * l3.length;
70284
+ }
 
70285
 
70286
+ console.log(totalComplexity);",node:14
70287
  2024,21,1,"--- Day 21: Keypad Conundrum ---
70288
 
70289
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
 
70370
  The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29.
70371
  In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384.
70372
 
70373
+ Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"// solution for https://adventofcode.com/2024/day/21 part 1
70374
+
70375
+ // this solution tests ALL combinations of the simplest commands!
70376
+
70377
+ ""use strict""
70378
+
70379
+ const input = Deno.readTextFileSync(""day21-input.txt"").trim()
70380
+
70381
+ const allCodes = [ ]
70382
+
70383
+ const numericCommandsByMove = { // simplest commands only
70384
+
70385
+ ""0 to 0"": [ ""A"" ],
70386
+ ""0 to 1"": [ ""^<A"" ],
70387
+ ""0 to 2"": [ ""^A"" ],
70388
+ ""0 to 3"": [ ""^>A"", "">^A"" ],
70389
+ ""0 to 4"": [ ""^^<A"" ],
70390
+ ""0 to 5"": [ ""^^A"" ],
70391
+ ""0 to 6"": [ ""^^>A"", "">^^A"" ],
70392
+ ""0 to 7"": [ ""^^^<A"" ],
70393
+ ""0 to 8"": [ ""^^^A"" ],
70394
+ ""0 to 9"": [ ""^^^>A"", "">^^^A"" ],
70395
+ ""0 to A"": [ "">A"" ],
70396
+ ""1 to 0"": [ "">vA"" ],
70397
+ ""1 to 1"": [ ""A"" ],
70398
+ ""1 to 2"": [ "">A"" ],
70399
+ ""1 to 3"": [ "">>A"" ],
70400
+ ""1 to 4"": [ ""^A"" ],
70401
+ ""1 to 5"": [ ""^>A"", "">^A"" ],
70402
+ ""1 to 6"": [ ""^>>A"", "">>^A"" ],
70403
+ ""1 to 7"": [ ""^^A"" ],
70404
+ ""1 to 8"": [ ""^^>A"", "">^^A"" ],
70405
+ ""1 to 9"": [ ""^^>>A"", "">>^^A"" ],
70406
+ ""1 to A"": [ "">>vA"" ],
70407
+ ""2 to 0"": [ ""vA"" ],
70408
+ ""2 to 1"": [ ""<A"" ],
70409
+ ""2 to 2"": [ ""A"" ],
70410
+ ""2 to 3"": [ "">A"" ],
70411
+ ""2 to 4"": [ ""^<A"", ""<^A"" ],
70412
+ ""2 to 5"": [ ""^A"" ],
70413
+ ""2 to 6"": [ ""^>A"", "">^A"" ],
70414
+ ""2 to 7"": [ ""^^<A"", ""<^^A"" ],
70415
+ ""2 to 8"": [ ""^^A"" ],
70416
+ ""2 to 9"": [ ""^^>A"", "">^^A"" ],
70417
+ ""2 to A"": [ ""v>A"", "">vA"" ],
70418
+ ""3 to 0"": [ ""v<A"", ""<vA"" ],
70419
+ ""3 to 1"": [ ""<<A"" ],
70420
+ ""3 to 2"": [ ""<A"" ],
70421
+ ""3 to 3"": [ ""A"" ],
70422
+ ""3 to 4"": [ ""^<<A"", ""<<^A"" ],
70423
+ ""3 to 5"": [ ""^<A"", ""<^A"" ],
70424
+ ""3 to 6"": [ ""^A"" ],
70425
+ ""3 to 7"": [ ""^^<<A"", ""<<^^A"" ],
70426
+ ""3 to 8"": [ ""^^<A"", ""<^^A"" ],
70427
+ ""3 to 9"": [ ""^^A"" ],
70428
+ ""3 to A"": [ ""vA"" ],
70429
+ ""4 to 0"": [ "">vvA"" ],
70430
+ ""4 to 1"": [ ""vA"" ],
70431
+ ""4 to 2"": [ ""v>A"", "">vA"" ],
70432
+ ""4 to 3"": [ ""v>>A"", "">>vA"" ],
70433
+ ""4 to 4"": [ ""A"" ],
70434
+ ""4 to 5"": [ "">A"" ],
70435
+ ""4 to 6"": [ "">>A"" ],
70436
+ ""4 to 7"": [ ""^A"" ],
70437
+ ""4 to 8"": [ ""^>A"", "">^A"" ],
70438
+ ""4 to 9"": [ ""^>>A"", "">>^A"" ],
70439
+ ""4 to A"": [ "">>vvA"" ],
70440
+ ""5 to 0"": [ ""vvA"" ],
70441
+ ""5 to 1"": [ ""v<A"", ""<vA"" ],
70442
+ ""5 to 2"": [ ""vA"" ],
70443
+ ""5 to 3"": [ ""v>A"", "">vA"" ],
70444
+ ""5 to 4"": [ ""<A"" ],
70445
+ ""5 to 5"": [ ""A"" ],
70446
+ ""5 to 6"": [ "">A"" ],
70447
+ ""5 to 7"": [ ""^<A"", ""<^A"" ],
70448
+ ""5 to 8"": [ ""^A"" ],
70449
+ ""5 to 9"": [ ""^>A"", "">^A"" ],
70450
+ ""5 to A"": [ ""vv>A"", "">vvA"" ],
70451
+ ""6 to 0"": [ ""vv<A"", ""<vvA"" ],
70452
+ ""6 to 1"": [ ""v<<A"", ""<<vA"" ],
70453
+ ""6 to 2"": [ ""v<A"", ""<vA"" ],
70454
+ ""6 to 3"": [ ""vA"" ],
70455
+ ""6 to 4"": [ ""<<A"" ],
70456
+ ""6 to 5"": [ ""<A"" ],
70457
+ ""6 to 6"": [ ""A"" ],
70458
+ ""6 to 7"": [ ""^<<A"", ""<<^A"" ],
70459
+ ""6 to 8"": [ ""^<A"", ""<^A"" ],
70460
+ ""6 to 9"": [ ""^A"" ],
70461
+ ""6 to A"": [ ""vvA"" ],
70462
+ ""7 to 0"": [ "">vvvA"" ],
70463
+ ""7 to 1"": [ ""vvA"" ],
70464
+ ""7 to 2"": [ ""vv>A"", "">vvA"" ],
70465
+ ""7 to 3"": [ ""vv>>A"", "">>vvA"" ],
70466
+ ""7 to 4"": [ ""vA"" ],
70467
+ ""7 to 5"": [ ""v>A"", "">vA"" ],
70468
+ ""7 to 6"": [ ""v>>A"", "">>vA"" ],
70469
+ ""7 to 7"": [ ""A"" ],
70470
+ ""7 to 8"": [ "">A"" ],
70471
+ ""7 to 9"": [ "">>A"" ],
70472
+ ""7 to A"": [ "">>vvvA"" ],
70473
+ ""8 to 0"": [ ""vvvA"" ],
70474
+ ""8 to 1"": [ ""vv<A"", ""<vvA"" ],
70475
+ ""8 to 2"": [ ""vvA"" ],
70476
+ ""8 to 3"": [ ""vv>A"", "">vvA"" ],
70477
+ ""8 to 4"": [ ""v<A"", ""<vA"" ],
70478
+ ""8 to 5"": [ ""vA"" ],
70479
+ ""8 to 6"": [ ""v>A"", "">vA"" ],
70480
+ ""8 to 7"": [ ""<A"" ],
70481
+ ""8 to 8"": [ ""A"" ],
70482
+ ""8 to 9"": [ "">A"" ],
70483
+ ""8 to A"": [ ""vvv>A"", "">vvvA"" ],
70484
+ ""9 to 0"": [ ""vvv<A"", ""<vvvA"" ],
70485
+ ""9 to 1"": [ ""vv<<A"", ""<<vvA"" ],
70486
+ ""9 to 2"": [ ""vv<A"", ""<vvA"" ],
70487
+ ""9 to 3"": [ ""vvA"" ],
70488
+ ""9 to 4"": [ ""v<<A"", ""<<vA"" ],
70489
+ ""9 to 5"": [ ""v<A"", ""<vA"" ],
70490
+ ""9 to 6"": [ ""vA"" ],
70491
+ ""9 to 7"": [ ""<<A"" ],
70492
+ ""9 to 8"": [ ""<A"" ],
70493
+ ""9 to 9"": [ ""A"" ],
70494
+ ""9 to A"": [ ""vvvA"" ],
70495
+ ""A to 0"": [ ""<A"" ],
70496
+ ""A to 1"": [ ""^<<A"" ],
70497
+ ""A to 2"": [ ""^<A"", ""<^A"" ],
70498
+ ""A to 3"": [ ""^A"" ],
70499
+ ""A to 4"": [ ""^^<<A"" ],
70500
+ ""A to 5"": [ ""^^<A"", ""<^^A"" ],
70501
+ ""A to 6"": [ ""^^A"" ],
70502
+ ""A to 7"": [ ""^^^<<A"" ],
70503
+ ""A to 8"": [ ""^^^<A"", ""<^^^A"" ],
70504
+ ""A to 9"": [ ""^^^A"" ],
70505
+ ""A to A"": [ ""A"" ]
70506
+ }
70507
+
70508
+ const directionalCommandsByMove = { // simplest commands only
70509
+
70510
+ ""^ to ^"": [ ""A"" ],
70511
+ ""^ to v"": [ ""vA"" ],
70512
+ ""^ to <"": [ ""v<A"" ],
70513
+ ""^ to >"": [ ""v>A"", "">vA"" ],
70514
+ ""^ to A"": [ "">A"" ],
70515
+
70516
+ ""v to ^"": [ ""^A"" ],
70517
+ ""v to v"": [ ""A"" ],
70518
+ ""v to <"": [ ""<A"" ],
70519
+ ""v to >"": [ "">A"" ],
70520
+ ""v to A"": [ ""^>A"", "">^A"" ],
70521
+
70522
+ ""< to ^"": [ "">^A"" ],
70523
+ ""< to v"": [ "">A"" ],
70524
+ ""< to <"": [ ""A"" ],
70525
+ ""< to >"": [ "">>A"" ],
70526
+ ""< to A"": [ "">>^A"" ],
70527
+
70528
+ ""> to ^"": [ ""^<A"", ""<^A"" ],
70529
+ ""> to v"": [ ""<A"" ],
70530
+ ""> to <"": [ ""<<A"" ],
70531
+ ""> to >"": [ ""A"" ],
70532
+ ""> to A"": [ ""^A"" ],
70533
+
70534
+ ""A to ^"": [ ""<A"" ],
70535
+ ""A to v"": [ ""v<A"", ""<vA"" ],
70536
+ ""A to <"": [ ""v<<A"" ],
70537
+ ""A to >"": [ ""vA"" ],
70538
+ ""A to A"": [ ""A"" ]
70539
+ }
70540
+
70541
+ const memory = { }
70542
+
70543
+
70544
+ function main() {
70545
+
70546
+ processInput()
70547
+
70548
+ let complexity = 0
70549
+
70550
+ for (const code of allCodes) { complexity += calcComplexityOf(code) }
70551
+
70552
+ console.log(""the answer is"", complexity)
70553
+ }
70554
+
70555
+ function processInput() {
70556
+
70557
+ const rawLines = input.split(""\n"")
70558
+
70559
+ for (const rawLine of rawLines) { allCodes.push(rawLine.trim()) }
70560
+ }
70561
+
70562
+ function calcComplexityOf(code) {
70563
+
70564
+ const initialSequences = generateInitialSequences(code)
70565
+
70566
+ const leastSteps = calcLeastSteps(initialSequences)
70567
+
70568
+ return parseInt(code) * leastSteps
70569
+ }
70570
+
70571
+ ///////////////////////////////////////////////////////////////////////////////
70572
+
70573
+ function generateInitialSequences(code) {
70574
+
70575
+ let lastButton = ""A""
70576
+
70577
+ let sequences = [ """" ]
70578
+
70579
+ for (const button of code) {
70580
+
70581
+ const temp = [ ]
70582
+
70583
+ const commands = numericCommandsByMove[lastButton + "" to "" + button]
70584
+
70585
+ lastButton = button
70586
+
70587
+ for (const command of commands) {
70588
+
70589
+ for (const sequence of sequences) { temp.push(sequence + command) }
70590
+ }
70591
+
70592
+ sequences = temp
70593
+ }
70594
+
70595
+ return sequences
70596
+ }
70597
+
70598
+ ///////////////////////////////////////////////////////////////////////////////
70599
+
70600
+ function calcLeastSteps(initialSequences) {
70601
+
70602
+ let minLength = Infinity
70603
+
70604
+ for (const sequence of initialSequences) {
70605
+
70606
+ const length = findFutureLength(sequence)
70607
+
70608
+ if (length < minLength) { minLength = length }
70609
+ }
70610
+
70611
+ return minLength
70612
+ }
70613
+
70614
+ function findFutureLength(sequence) {
70615
+
70616
+ const tokens = tokenize(sequence)
70617
+
70618
+ let length = 0
70619
+
70620
+ for (const token of tokens) { length += smallestFutureLengthForToken(token) }
70621
+
70622
+ return length
70623
+ }
70624
+
70625
+ function tokenize(sequence) {
70626
+
70627
+ const tokens = [ ]
70628
+
70629
+ let token = """"
70630
+
70631
+ for (const button of sequence) {
70632
+
70633
+ token += button
70634
+
70635
+ if (button == ""A"") { tokens. push(token); token = """" }
70636
+ }
70637
+ return tokens
70638
+ }
70639
+
70640
+ function smallestFutureLengthForToken(token) {
70641
+
70642
+ let minLength = Infinity
70643
+
70644
+ const sequences = generateSequencesFromToken(token, 2)
70645
+
70646
+ for (const sequence of sequences) {
70647
+
70648
+ if (sequence.length < minLength) { minLength = sequence.length }
70649
+ }
70650
+
70651
+ return minLength
70652
+ }
70653
+
70654
+ ///////////////////////////////////////////////////////////////////////////////
70655
+
70656
+ function generateSequencesFromToken(sourceToken, roundsToGo) {
70657
+
70658
+ if (roundsToGo == 0) { return [ sourceToken ] }
70659
+
70660
+ const id = sourceToken + ""~"" + roundsToGo
70661
+
70662
+ if (memory[id] != undefined) { return memory[id] }
70663
+
70664
+ //
70665
+
70666
+ let sequences = [ """" ]
70667
+
70668
+ let lastButton = ""A""
70669
+
70670
+ for (const button of sourceToken) {
70671
+
70672
+ const temp = [ ]
70673
+
70674
+ const newTokens = directionalCommandsByMove[lastButton + "" to "" + button]
70675
+
70676
+ lastButton = button
70677
+
70678
+ const listA = generateSequencesFromToken(newTokens[0], roundsToGo - 1)
70679
+
70680
+ let listB = [ ]
70681
+
70682
+ if (newTokens[1] != undefined) { listB = generateSequencesFromToken(newTokens[1], roundsToGo - 1) }
70683
+
70684
+ for (const sequence of sequences) {
70685
+
70686
+ for (const newSequence of listA) { temp.push(sequence + newSequence) }
70687
+ for (const newSequence of listB) { temp.push(sequence + newSequence) }
70688
+ }
70689
+
70690
+ sequences = temp
70691
+ }
70692
+
70693
+ memory[id] = sequences
70694
+ return sequences
70695
+ }
70696
+
70697
+ ///////////////////////////////////////////////////////////////////////////////
70698
+
70699
+ console.time(""execution time"")
70700
+ main()
70701
+ console.timeEnd(""execution time"") // 1ms",node:14
70702
+ 2024,21,1,"--- Day 21: Keypad Conundrum ---
70703
+
70704
+ As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
70705
+
70706
+ The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door.
70707
+
70708
+ The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this:
70709
+
70710
+ +---+---+---+
70711
+ | 7 | 8 | 9 |
70712
+ +---+---+---+
70713
+ | 4 | 5 | 6 |
70714
+ +---+---+---+
70715
+ | 1 | 2 | 3 |
70716
+ +---+---+---+
70717
+ | 0 | A |
70718
+ +---+---+
70719
+ Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead.
70720
+
70721
+ The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad.
70722
+
70723
+ The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this:
70724
+
70725
+ +---+---+
70726
+ | ^ | A |
70727
+ +---+---+---+
70728
+ | < | v | > |
70729
+ +---+---+---+
70730
+ When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm.
70731
+
70732
+ For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is:
70733
+
70734
+ < to move the arm from A (its initial position) to 0.
70735
+ A to push the 0 button.
70736
+ ^A to move the arm to the 2 button and push it.
70737
+ >^^A to move the arm to the 9 button and push it.
70738
+ vvvA to move the arm to the A button and push it.
70739
+ In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: <A^A>^^AvvvA, <A^A^>^AvvvA, and <A^A^^>AvvvA.
70740
+
70741
+ Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead.
70742
+
70743
+ When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad).
70744
+
70745
+ There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<<A>>^A<A>AvA<^AA>A<vAAA>^A.
70746
+
70747
+ Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too.
70748
+
70749
+ There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A.
70750
+
70751
+ Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself.
70752
+
70753
+ Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad:
70754
+
70755
+ <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A
70756
+ v<<A>>^A<A>AvA<^AA>A<vAAA>^A
70757
+ <A^A>^^AvvvA
70758
+ 029A
70759
+ In summary, there are the following keypads:
70760
+
70761
+ One directional keypad that you are using.
70762
+ Two directional keypads that robots are using.
70763
+ One numeric keypad (on a door) that a robot is using.
70764
+ It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is.
70765
+
70766
+ To unlock the door, five codes will need to be typed on its numeric keypad. For example:
70767
+
70768
+ 029A
70769
+ 980A
70770
+ 179A
70771
+ 456A
70772
+ 379A
70773
+ For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad:
70774
+
70775
+ 029A: <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A
70776
+ 980A: <v<A>>^AAAvA^A<vA<AA>>^AvAA<^A>A<v<A>A>^AAAvA<^A>A<vA>^A<A>A
70777
+ 179A: <v<A>>^A<vA<A>>^AAvAA<^A>A<v<A>>^AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A
70778
+ 456A: <v<A>>^AA<vA<A>>^AAvAA<^A>A<vA>^A<A>A<vA>^A<A>A<v<A>A>^AAvA<^A>A
70779
+ 379A: <v<A>>^AvA^A<vA<AA>>^AAvA<^A>AAvA^A<vA>^AA<A>A<v<A>A>^AAAvA<^A>A
70780
+ The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary.
70781
+
70782
+ The complexity of a single code (like 029A) is equal to the result of multiplying these two values:
70783
+
70784
+ The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68.
70785
+ The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29.
70786
+ In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384.
70787
+
70788
+ Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"const fs = require(""fs"");
70789
+
70790
+ const positionMap = {
70791
+ ""0"": [3, 1],
70792
+ ""1"": [2, 0],
70793
+ ""2"": [2, 1],
70794
+ ""3"": [2, 2],
70795
+ ""4"": [1, 0],
70796
+ ""5"": [1, 1],
70797
+ ""6"": [1, 2],
70798
+ ""7"": [0, 0],
70799
+ ""8"": [0, 1],
70800
+ ""9"": [0, 2],
70801
+ ""A"": [3, 2],
70802
+ """": [3, 0],
70803
+ };
70804
+
70805
+ const movementMap = {
70806
+ ""^"": [0, 1],
70807
+ ""A"": [0, 2],
70808
+ ""<"": [1, 0],
70809
+ ""v"": [1, 1],
70810
+ "">"": [1, 2],
70811
+ """": [0, 0],
70812
+ };
70813
+
70814
+ const directionMapping = {
70815
+ ""-1,0"": ""^"",
70816
+ ""1,0"": ""v"",
70817
+ ""0,-1"": ""<"",
70818
+ ""0,1"": "">"",
70819
+ };
70820
+
70821
+ function calculatePath(keyLocations, inputSequence) {
70822
+ let pathSequence = [];
70823
+
70824
+ for (let i = 0; i < inputSequence.length - 1; i++) {
70825
+ const start = keyLocations[inputSequence[i]];
70826
+ const end = keyLocations[inputSequence[i + 1]];
70827
+ const steps = [];
70828
+ const directions = [];
70829
+
70830
+ if (!start || !end) continue;
70831
+
70832
+ for (let y = start[1] - 1; y >= end[1]; y--) {
70833
+ steps.push([start[0], y]);
70834
+ directions.push([0, -1]);
70835
+ }
70836
+
70837
+ for (let x = start[0] + 1; x <= end[0]; x++) {
70838
+ steps.push([x, start[1]]);
70839
+ directions.push([1, 0]);
70840
+ }
70841
+
70842
+ for (let x = start[0] - 1; x >= end[0]; x--) {
70843
+ steps.push([x, start[1]]);
70844
+ directions.push([-1, 0]);
70845
+ }
70846
+
70847
+ for (let y = start[1] + 1; y <= end[1]; y++) {
70848
+ steps.push([start[0], y]);
70849
+ directions.push([0, 1]);
70850
+ }
70851
+
70852
+ if (steps.some((coord) => JSON.stringify(coord) === JSON.stringify(keyLocations[""""]))) {
70853
+ directions.reverse();
70854
+ }
70855
+
70856
+ pathSequence.push(...directions.map((direction) => directionMapping[direction.join("","")]), ""A"");
70857
+ }
70858
+
70859
+ return pathSequence.join("""");
70860
+ }
70861
+
70862
+ const inputData = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n"");
70863
+
70864
+ let totalScore = 0;
70865
+
70866
+ inputData.forEach((line) => {
70867
+ if (!line) return;
70868
+
70869
+ let pathToFirstStep = calculatePath(positionMap, ""A"" + line);
70870
+ let pathToSecondStep = calculatePath(movementMap, ""A"" + pathToFirstStep);
70871
+ let finalPath = calculatePath(movementMap, ""A"" + pathToSecondStep);
70872
+
70873
+ totalScore += parseInt(line.slice(0, -1)) * finalPath.length;
70874
+ });
70875
+
70876
+ console.log(totalScore);
70877
+ ",node:14
70878
  2024,21,1,"--- Day 21: Keypad Conundrum ---
70879
 
70880
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
 
71535
 
71536
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
71537
 
71538
+ Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"// solution for https://adventofcode.com/2024/day/21 part 2
71539
+
71540
+ // this solution doesn't check all combinations of directional commands
71541
+ // at any possible branch;
71542
+ // instead it uses only directional commands that performed better when
71543
+ // tested
71544
+
71545
+ ""use strict""
71546
+
71547
+ const input = Deno.readTextFileSync(""day21-input.txt"").trim()
71548
+
71549
+ const allCodes = [ ]
71550
+
71551
+ const numericCommandsByMove = { // simplest commands only
71552
+
71553
+ ""0 to 0"": [ ""A"" ],
71554
+ ""0 to 1"": [ ""^<A"" ],
71555
+ ""0 to 2"": [ ""^A"" ],
71556
+ ""0 to 3"": [ ""^>A"", "">^A"" ],
71557
+ ""0 to 4"": [ ""^^<A"" ],
71558
+ ""0 to 5"": [ ""^^A"" ],
71559
+ ""0 to 6"": [ ""^^>A"", "">^^A"" ],
71560
+ ""0 to 7"": [ ""^^^<A"" ],
71561
+ ""0 to 8"": [ ""^^^A"" ],
71562
+ ""0 to 9"": [ ""^^^>A"", "">^^^A"" ],
71563
+ ""0 to A"": [ "">A"" ],
71564
+ ""1 to 0"": [ "">vA"" ],
71565
+ ""1 to 1"": [ ""A"" ],
71566
+ ""1 to 2"": [ "">A"" ],
71567
+ ""1 to 3"": [ "">>A"" ],
71568
+ ""1 to 4"": [ ""^A"" ],
71569
+ ""1 to 5"": [ ""^>A"", "">^A"" ],
71570
+ ""1 to 6"": [ ""^>>A"", "">>^A"" ],
71571
+ ""1 to 7"": [ ""^^A"" ],
71572
+ ""1 to 8"": [ ""^^>A"", "">^^A"" ],
71573
+ ""1 to 9"": [ ""^^>>A"", "">>^^A"" ],
71574
+ ""1 to A"": [ "">>vA"" ],
71575
+ ""2 to 0"": [ ""vA"" ],
71576
+ ""2 to 1"": [ ""<A"" ],
71577
+ ""2 to 2"": [ ""A"" ],
71578
+ ""2 to 3"": [ "">A"" ],
71579
+ ""2 to 4"": [ ""^<A"", ""<^A"" ],
71580
+ ""2 to 5"": [ ""^A"" ],
71581
+ ""2 to 6"": [ ""^>A"", "">^A"" ],
71582
+ ""2 to 7"": [ ""^^<A"", ""<^^A"" ],
71583
+ ""2 to 8"": [ ""^^A"" ],
71584
+ ""2 to 9"": [ ""^^>A"", "">^^A"" ],
71585
+ ""2 to A"": [ ""v>A"", "">vA"" ],
71586
+ ""3 to 0"": [ ""v<A"", ""<vA"" ],
71587
+ ""3 to 1"": [ ""<<A"" ],
71588
+ ""3 to 2"": [ ""<A"" ],
71589
+ ""3 to 3"": [ ""A"" ],
71590
+ ""3 to 4"": [ ""^<<A"", ""<<^A"" ],
71591
+ ""3 to 5"": [ ""^<A"", ""<^A"" ],
71592
+ ""3 to 6"": [ ""^A"" ],
71593
+ ""3 to 7"": [ ""^^<<A"", ""<<^^A"" ],
71594
+ ""3 to 8"": [ ""^^<A"", ""<^^A"" ],
71595
+ ""3 to 9"": [ ""^^A"" ],
71596
+ ""3 to A"": [ ""vA"" ],
71597
+ ""4 to 0"": [ "">vvA"" ],
71598
+ ""4 to 1"": [ ""vA"" ],
71599
+ ""4 to 2"": [ ""v>A"", "">vA"" ],
71600
+ ""4 to 3"": [ ""v>>A"", "">>vA"" ],
71601
+ ""4 to 4"": [ ""A"" ],
71602
+ ""4 to 5"": [ "">A"" ],
71603
+ ""4 to 6"": [ "">>A"" ],
71604
+ ""4 to 7"": [ ""^A"" ],
71605
+ ""4 to 8"": [ ""^>A"", "">^A"" ],
71606
+ ""4 to 9"": [ ""^>>A"", "">>^A"" ],
71607
+ ""4 to A"": [ "">>vvA"" ],
71608
+ ""5 to 0"": [ ""vvA"" ],
71609
+ ""5 to 1"": [ ""v<A"", ""<vA"" ],
71610
+ ""5 to 2"": [ ""vA"" ],
71611
+ ""5 to 3"": [ ""v>A"", "">vA"" ],
71612
+ ""5 to 4"": [ ""<A"" ],
71613
+ ""5 to 5"": [ ""A"" ],
71614
+ ""5 to 6"": [ "">A"" ],
71615
+ ""5 to 7"": [ ""^<A"", ""<^A"" ],
71616
+ ""5 to 8"": [ ""^A"" ],
71617
+ ""5 to 9"": [ ""^>A"", "">^A"" ],
71618
+ ""5 to A"": [ ""vv>A"", "">vvA"" ],
71619
+ ""6 to 0"": [ ""vv<A"", ""<vvA"" ],
71620
+ ""6 to 1"": [ ""v<<A"", ""<<vA"" ],
71621
+ ""6 to 2"": [ ""v<A"", ""<vA"" ],
71622
+ ""6 to 3"": [ ""vA"" ],
71623
+ ""6 to 4"": [ ""<<A"" ],
71624
+ ""6 to 5"": [ ""<A"" ],
71625
+ ""6 to 6"": [ ""A"" ],
71626
+ ""6 to 7"": [ ""^<<A"", ""<<^A"" ],
71627
+ ""6 to 8"": [ ""^<A"", ""<^A"" ],
71628
+ ""6 to 9"": [ ""^A"" ],
71629
+ ""6 to A"": [ ""vvA"" ],
71630
+ ""7 to 0"": [ "">vvvA"" ],
71631
+ ""7 to 1"": [ ""vvA"" ],
71632
+ ""7 to 2"": [ ""vv>A"", "">vvA"" ],
71633
+ ""7 to 3"": [ ""vv>>A"", "">>vvA"" ],
71634
+ ""7 to 4"": [ ""vA"" ],
71635
+ ""7 to 5"": [ ""v>A"", "">vA"" ],
71636
+ ""7 to 6"": [ ""v>>A"", "">>vA"" ],
71637
+ ""7 to 7"": [ ""A"" ],
71638
+ ""7 to 8"": [ "">A"" ],
71639
+ ""7 to 9"": [ "">>A"" ],
71640
+ ""7 to A"": [ "">>vvvA"" ],
71641
+ ""8 to 0"": [ ""vvvA"" ],
71642
+ ""8 to 1"": [ ""vv<A"", ""<vvA"" ],
71643
+ ""8 to 2"": [ ""vvA"" ],
71644
+ ""8 to 3"": [ ""vv>A"", "">vvA"" ],
71645
+ ""8 to 4"": [ ""v<A"", ""<vA"" ],
71646
+ ""8 to 5"": [ ""vA"" ],
71647
+ ""8 to 6"": [ ""v>A"", "">vA"" ],
71648
+ ""8 to 7"": [ ""<A"" ],
71649
+ ""8 to 8"": [ ""A"" ],
71650
+ ""8 to 9"": [ "">A"" ],
71651
+ ""8 to A"": [ ""vvv>A"", "">vvvA"" ],
71652
+ ""9 to 0"": [ ""vvv<A"", ""<vvvA"" ],
71653
+ ""9 to 1"": [ ""vv<<A"", ""<<vvA"" ],
71654
+ ""9 to 2"": [ ""vv<A"", ""<vvA"" ],
71655
+ ""9 to 3"": [ ""vvA"" ],
71656
+ ""9 to 4"": [ ""v<<A"", ""<<vA"" ],
71657
+ ""9 to 5"": [ ""v<A"", ""<vA"" ],
71658
+ ""9 to 6"": [ ""vA"" ],
71659
+ ""9 to 7"": [ ""<<A"" ],
71660
+ ""9 to 8"": [ ""<A"" ],
71661
+ ""9 to 9"": [ ""A"" ],
71662
+ ""9 to A"": [ ""vvvA"" ],
71663
+ ""A to 0"": [ ""<A"" ],
71664
+ ""A to 1"": [ ""^<<A"" ],
71665
+ ""A to 2"": [ ""^<A"", ""<^A"" ],
71666
+ ""A to 3"": [ ""^A"" ],
71667
+ ""A to 4"": [ ""^^<<A"" ],
71668
+ ""A to 5"": [ ""^^<A"", ""<^^A"" ],
71669
+ ""A to 6"": [ ""^^A"" ],
71670
+ ""A to 7"": [ ""^^^<<A"" ],
71671
+ ""A to 8"": [ ""^^^<A"", ""<^^^A"" ],
71672
+ ""A to 9"": [ ""^^^A"" ],
71673
+ ""A to A"": [ ""A"" ]
71674
+ }
71675
+
71676
+ const directionalCommandsByMove = { // shortest and simplest commands only
71677
+
71678
+ ""^ to ^"": ""A"",
71679
+ ""^ to v"": ""vA"",
71680
+ ""^ to <"": ""v<A"",
71681
+ ""^ to >"": ""v>A"", // "">vA"" does not result in the shortest sequence
71682
+ ""^ to A"": "">A"",
71683
+
71684
+ ""v to ^"": ""^A"",
71685
+ ""v to v"": ""A"",
71686
+ ""v to <"": ""<A"",
71687
+ ""v to >"": "">A"",
71688
+ ""v to A"": ""^>A"", // "">^A"" does not result in the shortest sequence
71689
+
71690
+ ""< to ^"": "">^A"",
71691
+ ""< to v"": "">A"",
71692
+ ""< to <"": ""A"",
71693
+ ""< to >"": "">>A"",
71694
+ ""< to A"": "">>^A"",
71695
+
71696
+ ""> to ^"": ""<^A"", // ""^<A"" does not result in the shortest sequence
71697
+ ""> to v"": ""<A"",
71698
+ ""> to <"": ""<<A"",
71699
+ ""> to >"": ""A"",
71700
+ ""> to A"": ""^A"",
71701
+
71702
+ ""A to ^"": ""<A"",
71703
+ ""A to v"": ""<vA"", // ""v<A"" does not result in the shortest sequence
71704
+ ""A to <"": ""v<<A"",
71705
+ ""A to >"": ""vA"",
71706
+ ""A to A"": ""A""
71707
+ }
71708
+
71709
+ const memory = { }
71710
+
71711
+
71712
+ function main() {
71713
+
71714
+ processInput()
71715
+
71716
+ let complexity = 0
71717
+
71718
+ for (const code of allCodes) { complexity += calcComplexityOf(code) }
71719
+
71720
+ console.log(""the answer is"", complexity)
71721
+ }
71722
+
71723
+ function processInput() {
71724
+
71725
+ const rawLines = input.split(""\n"")
71726
+
71727
+ for (const rawLine of rawLines) { allCodes.push(rawLine.trim()) }
71728
+ }
71729
+
71730
+ function calcComplexityOf(code) {
71731
+
71732
+ const initialSequences = generateInitialSequences(code)
71733
+
71734
+ const leastSteps = calcLeastSteps(initialSequences)
71735
+
71736
+ return parseInt(code) * leastSteps
71737
+ }
71738
+
71739
+ ///////////////////////////////////////////////////////////////////////////////
71740
+
71741
+ function generateInitialSequences(code) {
71742
+
71743
+ let lastButton = ""A""
71744
+
71745
+ let sequences = [ """" ]
71746
+
71747
+ for (const button of code) {
71748
+
71749
+ const temp = [ ]
71750
+
71751
+ const commands = numericCommandsByMove[lastButton + "" to "" + button]
71752
+
71753
+ lastButton = button
71754
+
71755
+ for (const command of commands) {
71756
+
71757
+ for (const sequence of sequences) { temp.push(sequence + command) }
71758
+ }
71759
+
71760
+ sequences = temp
71761
+ }
71762
+
71763
+ return sequences
71764
+ }
71765
+
71766
+ ///////////////////////////////////////////////////////////////////////////////
71767
+
71768
+ function calcLeastSteps(initialSequences) {
71769
+
71770
+ let minLength = Infinity
71771
+
71772
+ for (const sequence of initialSequences) {
71773
+
71774
+ const length = findFutureLength(sequence)
71775
+
71776
+ if (length < minLength) { minLength = length }
71777
+ }
71778
+
71779
+ return minLength
71780
+ }
71781
+
71782
+ function findFutureLength(sequence) {
71783
+
71784
+ const tokens = tokenize(sequence)
71785
+
71786
+ let length = 0
71787
+
71788
+ for (const token of tokens) { length += findLengthFromExpandedToken(token, 25) }
71789
+
71790
+ return length
71791
+ }
71792
+
71793
+ function tokenize(sequence) {
71794
+
71795
+ const tokens = [ ]
71796
+
71797
+ let token = """"
71798
+
71799
+ for (const button of sequence) {
71800
+
71801
+ token += button
71802
+
71803
+ if (button == ""A"") { tokens. push(token); token = """" }
71804
+ }
71805
+ return tokens
71806
+ }
71807
+
71808
+ ///////////////////////////////////////////////////////////////////////////////
71809
+
71810
+ function findLengthFromExpandedToken(sourceToken, roundsToGo) {
71811
+
71812
+ if (roundsToGo == 0) { return sourceToken.length }
71813
+
71814
+ const id = sourceToken + ""~"" + roundsToGo
71815
+
71816
+ if (memory[id] != undefined) { return memory[id] }
71817
+
71818
+ //
71819
+
71820
+ let length = 0
71821
+
71822
+ let lastButton = ""A""
71823
+
71824
+ for (const button of sourceToken) {
71825
+
71826
+ const newToken = directionalCommandsByMove[lastButton + "" to "" + button]
71827
+
71828
+ lastButton = button
71829
+
71830
+ length += findLengthFromExpandedToken(newToken, roundsToGo - 1)
71831
+ }
71832
+
71833
+ memory[id] = length
71834
+ return length
71835
+ }
71836
+
71837
+ ///////////////////////////////////////////////////////////////////////////////
71838
+
71839
+ console.time(""execution time"")
71840
+ main()
71841
+ console.timeEnd(""execution time"") // 1ms",node:14
71842
  2024,21,2,"--- Day 21: Keypad Conundrum ---
71843
 
71844
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
 
71944
 
71945
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
71946
 
71947
+ Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"const fs = require('fs');
71948
+
71949
+ const NUMERIC_KEYS = {
71950
+ ""7"": [0, 0], ""8"": [1, 0], ""9"": [2, 0],
71951
+ ""4"": [0, 1], ""5"": [1, 1], ""6"": [2, 1],
71952
+ ""1"": [0, 2], ""2"": [1, 2], ""3"": [2, 2],
71953
+ ""0"": [1, 3], ""A"": [2, 3]
71954
+ };
71955
+
71956
+ const DIRECTIONAL_KEYS = {
71957
+ ""^"": [1, 0], ""A"": [2, 0],
71958
+ ""<"": [0, 1], ""v"": [1, 1], "">"": [2, 1]
71959
+ };
71960
+
71961
+ const ALLOWED_NUM_POS = new Set(Object.values(NUMERIC_KEYS).map(JSON.stringify));
71962
+ const ALLOWED_DIR_POS = new Set(Object.values(DIRECTIONAL_KEYS).map(JSON.stringify));
71963
+
71964
+ const input = fs.readFileSync('input.txt', 'utf8').split(""\n"").map(x => x.trim());
71965
+
71966
+ function findKeystrokes(src, target, directional) {
71967
+ if (JSON.stringify(src) === JSON.stringify(target)) return [""A""];
71968
+ if (!directional && !ALLOWED_NUM_POS.has(JSON.stringify(src))) return [];
71969
+ if (directional && !ALLOWED_DIR_POS.has(JSON.stringify(src))) return [];
71970
+
71971
+ const [x1, y1] = src;
71972
+ const [x2, y2] = target;
71973
+ let res = [];
71974
+
71975
+ if (x1 < x2) res = res.concat(findKeystrokes([x1 + 1, y1], target, directional).map(s => "">"" + s));
71976
+ if (x1 > x2) res = res.concat(findKeystrokes([x1 - 1, y1], target, directional).map(s => ""<"" + s));
71977
+ if (y1 < y2) res = res.concat(findKeystrokes([x1, y1 + 1], target, directional).map(s => ""v"" + s));
71978
+ if (y1 > y2) res = res.concat(findKeystrokes([x1, y1 - 1], target, directional).map(s => ""^"" + s));
71979
+
71980
+ return res;
71981
+ }
71982
+
71983
+ // Memoization to cache previous results of findShortestToClick to prevent redundant work
71984
+ const memoShortest = new Map();
71985
+ function findShortestToClick(a, b, depth = 2) {
71986
+ const key = `${a},${b},${depth}`;
71987
+ if (memoShortest.has(key)) {
71988
+ return memoShortest.get(key);
71989
+ }
71990
+
71991
+ const opts = findKeystrokes(DIRECTIONAL_KEYS[a], DIRECTIONAL_KEYS[b], true);
71992
+ if (depth === 1) {
71993
+ const minLen = Math.min(...opts.map(x => x.length));
71994
+ memoShortest.set(key, minLen);
71995
+ return minLen;
71996
+ }
71997
+
71998
+ const tmps = opts.map(o => {
71999
+ const tmp = [];
72000
+ tmp.push(findShortestToClick(""A"", o[0], depth - 1));
72001
+ for (let i = 1; i < o.length; i++) {
72002
+ tmp.push(findShortestToClick(o[i - 1], o[i], depth - 1));
72003
+ }
72004
+ return tmp.reduce((acc, val) => acc + val, 0);
72005
+ });
72006
+
72007
+ const minResult = Math.min(...tmps);
72008
+ memoShortest.set(key, minResult);
72009
+ return minResult;
72010
+ }
72011
+
72012
+ function findShortest(code, levels) {
72013
+ let pos = NUMERIC_KEYS[""A""];
72014
+ let shortest = 0;
72015
+
72016
+ for (let key of code) {
72017
+ const possibleKeySequences = findKeystrokes(pos, NUMERIC_KEYS[key], false);
72018
+ const tmps = possibleKeySequences.map(sequence => {
72019
+ const tmp = [];
72020
+ tmp.push(findShortestToClick(""A"", sequence[0], levels));
72021
+ for (let i = 1; i < sequence.length; i++) {
72022
+ tmp.push(findShortestToClick(sequence[i - 1], sequence[i], levels));
72023
+ }
72024
+ return tmp.reduce((acc, val) => acc + val, 0);
72025
+ });
72026
+
72027
+ pos = NUMERIC_KEYS[key];
72028
+ shortest += Math.min(...tmps);
72029
+ }
72030
+ return shortest;
72031
+ }
72032
+
72033
+ function findTotalComplexity(codes, levels) {
72034
+ const complexities = codes.map(code => {
72035
+ const s = findShortest(code, levels);
72036
+ return s * parseInt(code.slice(0, -1), 10);
72037
+ });
72038
+ return complexities.reduce((acc, val) => acc + val, 0);
72039
+ }
72040
+
72041
+ console.log(findTotalComplexity(input, 25));",node:14
72042
  2024,21,2,"--- Day 21: Keypad Conundrum ---
72043
 
72044
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
 
72144
 
72145
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
72146
 
72147
+ Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"const fs = require('fs');
72148
+
72149
+ const NUM_MAP = {
72150
+ ""7"": [0, 0], ""8"": [1, 0], ""9"": [2, 0],
72151
+ ""4"": [0, 1], ""5"": [1, 1], ""6"": [2, 1],
72152
+ ""1"": [0, 2], ""2"": [1, 2], ""3"": [2, 2],
72153
+ ""0"": [1, 3], ""A"": [2, 3]
72154
+ };
72155
+
72156
+ const DIR_MAP = {
72157
+ ""^"": [1, 0], ""A"": [2, 0],
72158
+ ""<"": [0, 1], ""v"": [1, 1], "">"": [2, 1]
72159
+ };
72160
+
72161
+ const NUM_POS_SET = new Set(Object.values(NUM_MAP).map(JSON.stringify));
72162
+ const DIR_POS_SET = new Set(Object.values(DIR_MAP).map(JSON.stringify));
72163
+
72164
+ const rawInput = fs.readFileSync('input.txt', 'utf8').split(""\n"").map(line => line.trim());
72165
+
72166
+ function generatePath(from, to, isDirectional) {
72167
+ if (JSON.stringify(from) === JSON.stringify(to)) return [""A""];
72168
+ if (!isDirectional && !NUM_POS_SET.has(JSON.stringify(from))) return [];
72169
+ if (isDirectional && !DIR_POS_SET.has(JSON.stringify(from))) return [];
72170
+
72171
+ const [xFrom, yFrom] = from;
72172
+ const [xTo, yTo] = to;
72173
+ let movements = [];
72174
+
72175
+ if (xFrom < xTo) movements = movements.concat(generatePath([xFrom + 1, yFrom], to, isDirectional).map(move => "">"" + move));
72176
+ if (xFrom > xTo) movements = movements.concat(generatePath([xFrom - 1, yFrom], to, isDirectional).map(move => ""<"" + move));
72177
+ if (yFrom < yTo) movements = movements.concat(generatePath([xFrom, yFrom + 1], to, isDirectional).map(move => ""v"" + move));
72178
+ if (yFrom > yTo) movements = movements.concat(generatePath([xFrom, yFrom - 1], to, isDirectional).map(move => ""^"" + move));
72179
+
72180
+ return movements;
72181
+ }
72182
+
72183
+ const memoization = new Map();
72184
+ function computeMinimalSteps(start, end, maxDepth = 2) {
72185
+ const cacheKey = `${start},${end},${maxDepth}`;
72186
+ if (memoization.has(cacheKey)) {
72187
+ return memoization.get(cacheKey);
72188
+ }
72189
+
72190
+ const options = generatePath(DIR_MAP[start], DIR_MAP[end], true);
72191
+ if (maxDepth === 1) {
72192
+ const minLength = Math.min(...options.map(opt => opt.length));
72193
+ memoization.set(cacheKey, minLength);
72194
+ return minLength;
72195
+ }
72196
+
72197
+ const stepOptions = options.map(option => {
72198
+ const steps = [];
72199
+ steps.push(computeMinimalSteps(""A"", option[0], maxDepth - 1));
72200
+ for (let i = 1; i < option.length; i++) {
72201
+ steps.push(computeMinimalSteps(option[i - 1], option[i], maxDepth - 1));
72202
+ }
72203
+ return steps.reduce((sum, step) => sum + step, 0);
72204
+ });
72205
+
72206
+ const minResult = Math.min(...stepOptions);
72207
+ memoization.set(cacheKey, minResult);
72208
+ return minResult;
72209
+ }
72210
+
72211
+ function calculateMinimalCost(sequence, depth) {
72212
+ let position = NUM_MAP[""A""];
72213
+ let totalCost = 0;
72214
+
72215
+ for (let digit of sequence) {
72216
+ const paths = generatePath(position, NUM_MAP[digit], false);
72217
+ const pathCosts = paths.map(path => {
72218
+ const cost = [];
72219
+ cost.push(computeMinimalSteps(""A"", path[0], depth));
72220
+ for (let i = 1; i < path.length; i++) {
72221
+ cost.push(computeMinimalSteps(path[i - 1], path[i], depth));
72222
+ }
72223
+ return cost.reduce((sum, cost) => sum + cost, 0);
72224
+ });
72225
+
72226
+ position = NUM_MAP[digit];
72227
+ totalCost += Math.min(...pathCosts);
72228
+ }
72229
+ return totalCost;
72230
+ }
72231
+
72232
+ function calculateTotalEffort(sequences, depth) {
72233
+ const efforts = sequences.map(sequence => {
72234
+ const cost = calculateMinimalCost(sequence, depth);
72235
+ return cost * parseInt(sequence.slice(0, -1), 10);
72236
+ });
72237
+ return efforts.reduce((total, effort) => total + effort, 0);
72238
+ }
72239
+
72240
+ console.log(calculateTotalEffort(rawInput, 25));",node:14
72241
  2024,21,2,"--- Day 21: Keypad Conundrum ---
72242
 
72243
  As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship.
 
72343
 
72344
  The door codes are the same this time around; only the number of robots and directional keypads has changed.
72345
 
72346
+ Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"const fs = require('fs');
72347
+
72348
+ // Read the input file
72349
+ const input = fs.readFileSync('input.txt', { encoding: ""utf8"", flag: ""r"" });
72350
+ const keypadCodes = input.split('\n');
72351
+
72352
+ // Keypad and Directional Pad definitions
72353
+ const keypad = [
72354
+ ['7', '8', '9'],
72355
+ ['4', '5', '6'],
72356
+ ['1', '2', '3'],
72357
+ [null, '0', 'A'],
72358
+ ];
72359
+
72360
+ const dirpad = [
72361
+ [null, '^', 'A'],
72362
+ ['<', 'v', '>']
72363
+ ];
72364
+
72365
+ // Function to count occurrences of characters in a string
72366
+ const count = (str) => {
72367
+ let countObj = {};
72368
+ for (let char of str) {
72369
+ countObj[char] = (countObj[char] || 0) + 1;
72370
+ }
72371
+ return countObj;
72372
+ };
72373
+
72374
+ // Function to calculate all shortest best paths on the grid
72375
+ const allShortestBest = (start, grid) => {
72376
+ let pathsObj = {};
72377
+ let seen = new Set();
72378
+ seen.add(start.join('|'));
72379
+ let startVal = grid[start[0]][start[1]];
72380
+ let queue = [[[start, '', startVal]]];
72381
+
72382
+ const nextStep = ([r, c], grid) => {
72383
+ return [[r - 1, c, '^'], [r, c + 1, '>'], [r + 1, c, 'v'], [r, c - 1, '<']].filter(([nr, nc, nd]) =>
72384
+ grid?.[nr]?.[nc] !== undefined && !seen.has(`${nr}|${nc}`) && !!grid?.[nr]?.[nc]
72385
+ ).map(([nr, nc, nd]) => [[nr, nc], nd].concat(grid[nr][nc]));
72386
+ };
72387
+
72388
+ while (queue.length > 0) {
72389
+ let nextQueue = [];
72390
+ let queueSeen = [];
72391
+
72392
+ queue.forEach((path) => {
72393
+ let [point, dir, val] = path.at(-1);
72394
+ let next = nextStep(point, grid);
72395
+
72396
+ next.forEach(([np, nd, nv]) => {
72397
+ queueSeen.push(np.join('|'));
72398
+ let newPath = path.concat([[np, nd, nv]]);
72399
+ pathsObj[nv] ? pathsObj[nv].push(newPath.map((x) => x[1]).join('')) : pathsObj[nv] = [newPath.map((x) => x[1]).join('')];
72400
+ nextQueue.push(newPath);
72401
+ });
72402
+ });
72403
+
72404
+ queueSeen.forEach((x) => seen.add(x));
72405
+ queue = nextQueue;
72406
+ }
72407
+
72408
+ let bestPaths = {};
72409
+
72410
+ Object.entries(pathsObj).forEach(([k, paths]) => {
72411
+ if (paths.length === 1) {
72412
+ bestPaths[`${startVal}${k}`] = `${paths[0]}A`;
72413
+
72414
+ if (startVal === 'A') bestPaths[k] = `${paths[0]}A`;
72415
+ } else {
72416
+ let order = '<v^>';
72417
+ const pathscore = (path) => {
72418
+ let split = path.split('');
72419
+
72420
+ return split.slice(0, -1).map((y, yx) => {
72421
+ let score = 0;
72422
+ if (y !== split[yx + 1]) score += 10;
72423
+
72424
+ if (order.indexOf(split[yx + 1]) < order.indexOf(y)) score += 5;
72425
+
72426
+ return score;
72427
+ }).reduce((a, b) => a + b, 0);
72428
+ };
72429
+
72430
+ let scores = paths.map((x) => [pathscore(x), x]).sort((a, c) => a[0] - c[0]);
72431
+
72432
+ bestPaths[`${startVal}${k}`] = `${scores[0][1]}A`;
72433
+
72434
+ if (startVal === 'A') bestPaths[k] = `${scores[0][1]}A`;
72435
+ }
72436
+ });
72437
+ return bestPaths;
72438
+ };
72439
+
72440
+ let numpadDirs = Object.assign(...keypad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], keypad)));
72441
+
72442
+ let dirs = Object.assign(...dirpad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], dirpad)));
72443
+ dirs['A'] = 'A';
72444
+ dirs['AA'] = 'A';
72445
+ dirs['<<'] = 'A';
72446
+ dirs['>>'] = 'A';
72447
+ dirs['^^'] = 'A';
72448
+ dirs['vv'] = 'A';
72449
+
72450
+ const codes = keypadCodes.map((x) => [''].concat(x.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1)).map((x) => x.map((y) => numpadDirs[y])); // First keyboard, array of button presses e.g. ['<A','^A','>^^A','vvvA'] for example
72451
+
72452
+ // Function to calculate the minimum presses required
72453
+ const minPresses = (keypadCodes, dircodes, keyboards) => {
72454
+ let keypadNums = keypadCodes.map((x) => parseInt(x.slice(0, -1)));
72455
+ let targetDepth = keyboards - 1;
72456
+ let result = 0;
72457
+
72458
+ for (const [index, code] of dircodes.entries()) {
72459
+ let countObj = count(code);
72460
+
72461
+ for (let i = 0; i < targetDepth; i++) {
72462
+ let newCountObj = {};
72463
+ for (const [key, val] of Object.entries(countObj)) {
72464
+ if (key.length === 1) {
72465
+ let newKey = dirs[key];
72466
+
72467
+ newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val;
72468
+ } else {
72469
+ let keySplit = [''].concat(key.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1);
72470
+
72471
+ keySplit.forEach((sKey) => {
72472
+ let newKey = dirs[sKey];
72473
+ newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val;
72474
+ });
72475
+ }
72476
+ }
72477
+ countObj = newCountObj;
72478
+ }
72479
+
72480
+ result += (Object.entries(countObj).map(([k, v]) => k.length * v).reduce((a, b) => a + b, 0) * keypadNums[index]);
72481
+ }
72482
+ return result;
72483
+ };
72484
+
72485
+ // Performance tracking and calculation
72486
+ const t0 = performance.now();
72487
+ let p1 = minPresses(keypadCodes, codes, 3);
72488
+ const t1 = performance.now();
72489
+
72490
+ let p2 = minPresses(keypadCodes, codes, 26);
72491
+ const t2 = performance.now();
72492
+
72493
+ console.log('Part 1 answer is ', p1, t1 - t0, 'ms');
72494
+ console.log('Part 2 answer is ', p2, t2 - t1, 'ms');
72495
+
72496
+ // Old list of hardcoded directions (commented out for clarity)
72497
+ const olddirs = {
72498
+ '<': 'v<<A',
72499
+ '^': '<A',
72500
+ 'v': '<vA',
72501
+ '>': 'vA',
72502
+ 'A': 'A',
72503
+ '<^': '>^A',
72504
+ '<v': '>A',
72505
+ '<>': '>>A',
72506
+ '<A': '>>^A',
72507
+ '^<': 'v<A',
72508
+ '^v': 'vA',
72509
+ '^>': 'v>A',
72510
+ '^A': '>A',
72511
+ 'v<': '<A',
72512
+ 'v^': '^A',
72513
+ 'v>': '>A',
72514
+ 'vA': '^>A',
72515
+ '><': '<<A',
72516
+ '>v': '<A',
72517
+ '>^': '<^A',
72518
+ '>A': '^A',
72519
+ 'A<': 'v<<A',
72520
+ 'A^': '<A',
72521
+ 'Av': 'v<A',
72522
+ 'A>': 'vA',
72523
+ '<<': 'A',
72524
+ 'vv': 'A',
72525
+ '^^': 'A',
72526
+ '>>': 'A',
72527
+ 'AA': 'A'
72528
+ };",node:14
72529
  2024,22,1,"--- Day 22: Monkey Market ---
72530
 
72531
  As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief.