diff --git "a/aoc.csv" "b/aoc.csv" --- "a/aoc.csv" +++ "b/aoc.csv" @@ -29004,7 +29004,7 @@ de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. -What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","from collections import defaultdict +What is the password to get into the LAN party?","bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr","from collections import defaultdict def bron_kerbosch(connections, R, P, X): if len(P) == 0 and len(X) == 0: @@ -29113,7 +29113,7 @@ de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. -What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","f = open(""input.23.txt"") +What is the password to get into the LAN party?","bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr","f = open(""input.23.txt"") graph = {} for p in f: @@ -29243,7 +29243,7 @@ de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. -What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","from collections import defaultdict +What is the password to get into the LAN party?","bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr","from collections import defaultdict import itertools def is_clique(connections, nodes): @@ -29362,7 +29362,7 @@ de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. -What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","from collections import defaultdict +What is the password to get into the LAN party?","bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr","from collections import defaultdict from copy import deepcopy with open(""input.txt"") as input_file: @@ -29477,7 +29477,7 @@ de-ta ka-de The LAN party posters say that the password to get into the LAN party is the name of every computer at the LAN party, sorted alphabetically, then joined together with commas. (The people running the LAN party are clearly a bunch of nerds.) In this example, the password would be co,de,ka,ta. -What is the password to get into the LAN party?","bd,bu,dv,gl,dayc,rn,so,tm,wf,yl,ys,ze,zr","def parse() -> list[tuple[str]]: +What is the password to get into the LAN party?","bd,bu,dv,gl,qc,rn,so,tm,wf,yl,ys,ze,zr","def parse() -> list[tuple[str]]: return [(line.strip().split(""-"")[0], line.strip().split(""-"")[1]) for line in open(""input.txt"").readlines()] def generate_graph(connections) -> dict: @@ -30740,7 +30740,7 @@ In this example, two pairs of gates have outputs that are involved in a swap. By Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. -Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","class Gate: +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tqr,vmv,z07,z20,z28","class Gate: def __init__(self, inputs, op, label): self.inputs = inputs self.op = op @@ -31113,7 +31113,7 @@ In this example, two pairs of gates have outputs that are involved in a swap. By Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. -Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","with open('input.txt') as f: +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tqr,vmv,z07,z20,z28","with open('input.txt') as f: lines = f.read().splitlines() output_to_expr = dict() @@ -31413,7 +31413,7 @@ In this example, two pairs of gates have outputs that are involved in a swap. By Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. -Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","from typing import List, Dict +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tqr,vmv,z07,z20,z28","from typing import List, Dict from collections import defaultdict from part1 import parse_input @@ -31760,7 +31760,7 @@ In this example, two pairs of gates have outputs that are involved in a swap. By Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. -Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","def get_expr_for_output(output): +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tqr,vmv,z07,z20,z28","def get_expr_for_output(output): return output_to_expr[swaps.get(output, output)] def get_output_for_expr(expr): @@ -32036,7 +32036,7 @@ In this example, two pairs of gates have outputs that are involved in a swap. By Of course, your actual system is much more complex than this, and the gates that need their outputs swapped could be anywhere, not just attached to a wire starting with z. If you were to determine that you need to swap output wires aaa with eee, ooo with z99, bbb with ccc, and aoc with z24, your answer would be aaa,aoc,bbb,ccc,eee,ooo,z24,z99. -Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tdayr,vmv,z07,z20,z28","#day 24 +Your system of gates and wires has four pairs of gates which need their output wires swapped - eight wires in total. Determine which four pairs of gates need their outputs swapped so that your system correctly performs addition; what do you get if you sort the names of the eight wires involved in a swap and then join those names with commas?","hnv,hth,kfm,tqr,vmv,z07,z20,z28","#day 24 import os from functools import cache import re @@ -37272,192 +37272,164 @@ firstLocations.forEach((firstLocation) => { }); console.log(similarityScore);",node:14 -2024,1,1,"--- Day 1: Historian Hysteria --- - -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. +2024,3,1,"--- Day 3: Mull It Over --- -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. -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! +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" -You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +For example, consider the following section of corrupted memory: -For example: +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"const fs = require('fs'); -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +const input = fs.readFileSync('input.txt', 'utf8'); -In the example list above, the pairs and distances would be as follows: +const pattern = /mul\((\d+),(\d+)\)/g; -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! +let sum = 0; -Your actual left and right lists contain many location IDs. What is the total distance between your lists?",2378066,"const fs = require('fs'); +let match; +while ((match = pattern.exec(input)) !== null) { + sum += match[1] * match[2]; +} -const input = fs.readFileSync('./input.txt', 'utf8').trim().split('\n'); -const leftList = []; -const rightList = []; +console.log(sum);",node:14 +2024,3,1,"--- Day 3: Mull It Over --- -input.forEach(line => { - const [left, right] = line.split(' ').map(Number); - leftList.push(left); - rightList.push(right); -}); +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. -// Part 1 -function calculateTotalDistance(leftList, rightList) { - const sortedLeft = [...leftList].sort((a, b) => a - b); - const sortedRight = [...rightList].sort((a, b) => a - b); - let totalDistance = 0; - for (let i = 0; i < sortedLeft.length; i++) { - totalDistance += Math.abs(sortedLeft[i] - sortedRight[i]); - } - return totalDistance; -} +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" -// Part 2 -function calculateSimilarityScore(leftList, rightList) { - const frequencyMap = new Map(); - rightList.forEach(num => { - frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1); - }); +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! - let similarityScore = 0; - leftList.forEach(num => { - const count = frequencyMap.get(num) || 0; - similarityScore += num * count; - }); - return similarityScore; -} +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. -const totalDistance = calculateTotalDistance(leftList, rightList); -console.log('Part 1 - Total Distance:', totalDistance); -const similarityScore = calculateSimilarityScore(leftList, rightList); -console.log('Part 2 - Similarity Score:', similarityScore);",node:14 -2024,1,1,"--- Day 1: Historian Hysteria --- +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. +For example, consider the following section of corrupted memory: -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). -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! +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"// PART 1 -You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. +const fs = require('fs'); +const path = require('path'); -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? +// Resolve the file path +const filePath = path.join(__dirname, 'input.txt'); +const filePathTest1 = path.join(__dirname, 'test-1.txt'); +const filePathTest2 = path.join(__dirname, 'test-2.txt'); -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +// Read the file +function readFile(filePath) { + try { + const data = fs.readFileSync(filePath, 'utf8'); + return data; + } catch (err) { + console.error('Error reading the file:', err); + return null; + } +} -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +const string = readFile(filePath); +const stringTest1 = readFile(filePathTest1); +const stringTest2 = readFile(filePathTest2); -For example: +// Match any group of 1-3 digits, separated by a comma, between ""mul("" and "")"" +const regex = /(?<=mul\()(\d{1,3},\d{1,3})(?=\))/g; +const arrayOfMatches = (string.match(regex)).map((el) => el.split(',').map(Number)); -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. +const arrayMultiplied = arrayOfMatches.map((el => el.reduce((a , b) => a * b))); +const arraySummed = arrayMultiplied.reduce((a, b) => a + b); -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +console.log(arraySummed); -In the example list above, the pairs and distances would be as follows: +// PART 2 -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! +// Regex to find string between ""don't()"" and ""do()"" +const regexPart2 = /don't\(\).*?do\(\)/g; -Your actual left and right lists contain many location IDs. What is the total distance between your lists?",2378066,"let fs = require('fs'); -let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); +// Create first array of matches +let arrayofMarchesPart2 = string.split(regexPart2).filter(Boolean); -let firstLocations = []; -let secondLocations = []; +// Regex to find ""don't()"" without a following ""do()"" +const regexRemoveAfterLastDont = /don't\(\)(?!.*do\(\)).*/; -puzzleInput.forEach((line) => { - let parseLine = line.split(' '); - - if (parseLine[0] != '') firstLocations.push(parseLine[0]); - if (parseLine[1] != '') secondLocations.push(parseLine[1]); +// Remove for each array element anything after the last ""don't()"" if no ""do()"" exists +arrayofMarchesPart2 = arrayofMarchesPart2.map(element => { + if (regexRemoveAfterLastDont.test(element)) { + return element.replace(regexRemoveAfterLastDont, ''); + } + return element; // Return the element unchanged if the condition is not met }); -let sortedFirstLocations = firstLocations.sort(); -let sortedSecondLocations = secondLocations.sort(); +const arrayofMarchesPart2Bis = (arrayofMarchesPart2.map((el => (el.match(regex)).map((el) => el.split(',').map(Number))))).flat(1); +const arrayMultipliedPart2 = arrayofMarchesPart2Bis.map((el => el.reduce((a , b) => a * b))); +const arraySummedPart2 = arrayMultipliedPart2.reduce((a, b) => a + b); -let accumulatedDistance = 0; +console.log(arraySummedPart2);",node:14 +2024,3,1,"--- Day 3: Mull It Over --- -sortedFirstLocations.forEach((location, index) => { - let difference = location - sortedSecondLocations[index]; +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. - if (difference < 0) { - difference = difference * -1; - } +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" - accumulatedDistance += difference; -}); +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! -console.log(accumulatedDistance);",node:14 -2024,1,1,"--- Day 1: Historian Hysteria --- +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. +For example, consider the following section of corrupted memory: -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! +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). -You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"let fs = require('fs'); +let puzzleInput = fs.readFileSync('input.txt').toString(); -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? +let mul = (a, b) => a * b; -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +let regexp = /mul\([0-9]{1,3},[0-9]{1,3}\)/g; +let multiplications = puzzleInput.match(regexp); -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +let total = 0; -For example: +multiplications.forEach((thisMul) => { + let mulValue = eval(thisMul); -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. + total += mulValue; +}) -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +console.log(total);",node:14 +2024,3,1,"--- Day 3: Mull It Over --- -In the example list above, the pairs and distances would be as follows: +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" -Your actual left and right lists contain many location IDs. What is the total distance between your lists?",2378066,"const fs = require(""fs""); +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + +For example, consider the following section of corrupted memory: + +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"const fs = require(""fs""); let buffer, input, rows; @@ -37470,14291 +37442,25103 @@ try { input = buffer.toString(); rows = input.split(""\n""); -const left_list = []; -const right_list = []; +const multiply_sum = rows.reduce((accumulator, row) => { + if (row === """") return accumulator; // Empty row check, skip + let sum = 0; + let results; -rows.forEach((row) => { - if (row === """") { - return; + // Match mul(x,y) from row as string + const regex = /mul\((\d+)\,(\d+)\)/g; + while ((results = regex.exec(row)) !== null) { + // Match numbers from mul(x,y) + sum += Number(results[1]) * Number(results[2]); + // console.log(`Found ${results[1]} x ${results[2]} at ${results.index}.`); } - const nums = row.split("" ""); - left_list.push(Number(nums[0])); - right_list.push(Number(nums[1])); -}); - -left_list.sort(); -right_list.sort(); -const total_distance = left_list.reduce((accumulator, item, index) => { - return accumulator + Math.abs(right_list[index] - item); + return accumulator + sum; }, 0); -console.log({ total_distance });",node:14 -2024,1,1,"--- Day 1: Historian Hysteria --- - -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. - -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on 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 haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. - -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? +console.log({ multiply_sum });",node:14 +2024,3,1,"--- Day 3: Mull It Over --- -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" -For example: +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. -In the example list above, the pairs and distances would be as follows: +For example, consider the following section of corrupted memory: -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). -Your actual left and right lists contain many location IDs. What is the total distance between your lists?",2378066,"const fs = require('fs'); +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"const fs = require('fs'); -// Read the input file, validate file +// Read the input file const data = fs.readFileSync('input.txt', 'utf8'); -// Parse the input data const lines = data.trim().split('\n'); -let leftList = []; -let rightList = []; +let totalSum = 0; + +//Constructs regex to match criteria: +//mul(number1, number2) where number1 and number2 are 1-3 digit numbers +const regex = /mul\((\d{1,3}),(\d{1,3})\)/g; lines.forEach(line => { - const [left, right] = line.split(/\s+/).map(Number); - leftList.push(left); - rightList.push(right); + let match; + //regex.exec finds all the matches + while ((match = regex.exec(line)) !== null) { + //Parses the string to return an integer as a base10 (standard numeric output) + const number1 = parseInt(match[1], 10); + const number2 = parseInt(match[2], 10); + totalSum += number1 * number2; + } }); +console.log(`Total sum of all multiplied numbers: ${totalSum}`);",node:14 +2024,3,2,"--- Day 3: Mull It Over --- -// Sort both lists -leftList.sort((a, b) => a - b); -rightList.sort((a, b) => a - b); - -// Calculate the absolute distance -let totalDistance = 0; -for (let i = 0; i < leftList.length; i++) { - totalDistance += Math.abs(leftList[i] - rightList[i]); -} +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. -console.log('Total Distance:', totalDistance);",node:14 -2024,1,1,"--- Day 1: Historian Hysteria --- +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. -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! +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. -You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. +For example, consider the following section of corrupted memory: -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +Your puzzle answer was 170807108. -For example: +--- Part Two --- -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +There are two new instructions you'll need to handle: -In the example list above, the pairs and distances would be as follows: +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! +For example: -Your actual left and right lists contain many location IDs. What is the total distance between your lists? +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. -Your puzzle answer was 2378066. +This time, the sum of the results is 48 (2*4 + 8*5). ---- Part Two --- +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"let fs = require('fs'); +let puzzleInput = fs.readFileSync('input.txt').toString(); -Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. +let mul = (a, b) => a * b; -Or are they? +let regEx = /do\(\)|don\'t\(\)|mul\([0-9]{1,3},[0-9]{1,3}\)/g; +let parts = puzzleInput.match(regEx); -The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. +let doing = true; +let total = 0; -This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. +parts.forEach((part) => { + if (doing && part.substring(0, 3) == 'mul') { + let value = eval(part); + total += value; + } -Here are the same example lists again: + if (part.substring(0, 3) == 'do(') doing = true; + if (part.substring(0, 3) == 'don') doing = false; +}); -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -For these example lists, here is the process of finding the similarity score: +console.log(total);",node:14 +2024,3,2,"--- Day 3: Mull It Over --- -The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. -The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. -The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). -The fourth number, 1, also does not appear in the right list. -The fifth number, 3, appears in the right list three times; the similarity score increases by 9. -The last number, 3, appears in the right list three times; the similarity score again increases by 9. -So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. -Once again consider your left and right lists. What is their similarity score?",2378066,"const fs = require('fs'); +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" -// Function to calculate the total distance -function calculateTotalDistance(leftList, rightList) { - // Sort both lists and calculate the sum of absolute differences - return leftList - .sort((a, b) => a - b) - .map((left, index) => Math.abs(left - rightList.sort((a, b) => a - b)[index])) - .reduce((sum, distance) => sum + distance, 0); -} +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! -// Read the input file and process data -fs.readFile('input.txt', 'utf-8', (err, data) => { - if (err) { - console.error('Error reading file:', err); - return; - } +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. - // Parse input data into left and right lists - const [leftList, rightList] = data - .trim() - .split('\n') - .reduce( - ([left, right], line) => { - const [l, r] = line.split(/\s+/).map(Number); - left.push(l); - right.push(r); - return [left, right]; - }, - [[], []] // Initial empty arrays for left and right - ); +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. - // Calculate and output the total distance - const totalDistance = calculateTotalDistance(leftList, rightList); - console.log('Total Distance:', totalDistance); -});",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- +For example, consider the following section of corrupted memory: -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? -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! +Your puzzle answer was 170807108. -You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. +--- Part Two --- -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +There are two new instructions you'll need to handle: -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. For example: -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +This time, the sum of the results is 48 (2*4 + 8*5). -In the example list above, the pairs and distances would be as follows: +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require('fs'); -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! +// Read the input file +const data = fs.readFileSync('input.txt', 'utf8'); +const inputString = data.trim(); -Your actual left and right lists contain many location IDs. What is the total distance between your lists? +let totalSum = 0; +let mulEnabled = true; -Your puzzle answer was 2378066. +const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g; ---- Part Two --- +let match; +while ((match = instructionRegex.exec(inputString)) !== null) { + if (match[1]) { + // Matched 'do()' + mulEnabled = true; + } else if (match[2]) { + // Matched ""don't()"" + mulEnabled = false; + } else if (match[3] && mulEnabled) { + // Matched 'mul(X,Y)' and mul is enabled + const number1 = parseInt(match[3], 10); + const number2 = parseInt(match[4], 10); + totalSum += number1 * number2; + } +} -Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. +console.log(`Total sum of all multiplied numbers: ${totalSum}`);",node:14 +2024,3,2,"--- Day 3: Mull It Over --- -Or are they? - -The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. - -This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. - -Here are the same example lists again: - -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -For these example lists, here is the process of finding the similarity score: - -The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. -The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. -The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). -The fourth number, 1, also does not appear in the right list. -The fifth number, 3, appears in the right list three times; the similarity score increases by 9. -The last number, 3, appears in the right list three times; the similarity score again increases by 9. -So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). - -Once again consider your left and right lists. What is their similarity score?",18934359,"const fs = require(""fs""); -let input = fs.readFileSync(""input.txt"", ""utf-8""); -input = input.split(/\r?\n/).map((row) => row.split("" "")); -const firstCol = input.map((row) => row[0]); -const secondCol = input.map((row) => row[1]); - -const firstSolution = () => { - const firstColSorted = firstCol.sort(); - const secondColSorted = secondCol.sort(); - const distances = firstColSorted.map((firstColValue, index) => - Math.abs(firstColValue - secondColSorted[index]) - ); - - return distances.reduce((acc, value) => acc + value, 0); -}; - -console.log(""first part result:"", firstSolution()); - -const secondSolution = () => { - const similarity = firstCol.map( - (firstColValue) => - firstColValue * - secondCol.filter((secondColValue) => secondColValue === firstColValue) - .length - ); - - return similarity.reduce((acc, value) => acc + value, 0); -}; - -console.log(""second part result:"", secondSolution());",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- - -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. - -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on 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 haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. - -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? - -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" -For example: +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. -In the example list above, the pairs and distances would be as follows: +For example, consider the following section of corrupted memory: -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). -Your actual left and right lists contain many location IDs. What is the total distance between your lists? +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? -Your puzzle answer was 2378066. +Your puzzle answer was 170807108. --- Part Two --- -Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. - -Or are they? +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. -The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. +There are two new instructions you'll need to handle: -This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. -Here are the same example lists again: +For example: -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -For these example lists, here is the process of finding the similarity score: +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. -The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. -The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. -The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). -The fourth number, 1, also does not appear in the right list. -The fifth number, 3, appears in the right list three times; the similarity score increases by 9. -The last number, 3, appears in the right list three times; the similarity score again increases by 9. -So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). +This time, the sum of the results is 48 (2*4 + 8*5). -Once again consider your left and right lists. What is their similarity score?",18934359,"const fs = require(""fs""); +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require(""fs""); const path = require(""path""); const fileTxt = fs.readFileSync(path.join(__dirname, ""input.txt"")); const inputFromAdvent = fileTxt.toString(); const parseInput = (input) => { - const parsedInput = input - .trim() - .split(""\n"") - .reduce( - (acc, item) => { - const [first, second] = item.split("" "").filter(Boolean); - acc[0].push(Number(first)); - acc[1].push(Number(second)); - return acc; - }, - [[], []] - ); - - return parsedInput; -}; - -const orderLists = (input) => { - const [first, second] = input; - const orderedFirst = first.sort((a, b) => a - b); - const orderedSecond = second.sort((a, b) => a - b); - return [orderedFirst, orderedSecond]; -}; - -const getDistance = (input) => { - const distanceArray = []; - const [first, second] = orderLists(input); - for (let i = 0; i < first.length; i++) { - distanceArray.push(Math.abs(first[i] - second[i])); - } - - return distanceArray; + // want to take only between () and comma inside after mul. Eg mul(2,4) 2,4 + const regex = /mul\((\d+),(\d+)\)/g; + const matches = input.match(regex); + return matches.map((match) => match.slice(4, -1).split("","").map(Number)); }; -const sumDistance = (input) => { - return input.reduce((acc, item) => acc + item, 0); +const parseAndMultiplyInput = (input) => { + return input + .split(""do()"") // split into chunks + .map((chunk) => chunk.split(""don't()"")[0]) // remove don't() + .map((s) => [...s.matchAll(/mul\((\d+),(\d+)\)/g)]) // find all mul pairs + .flatMap((m) => m.map((m) => m[1] * m[2])) // multiply pairs + .reduce((acc, curr) => acc + curr, 0); // sum up }; -const getTotalDistance = (input) => { - const [arrayA, arrayB] = input - .trim() - .split(""\n"") - .reduce( - (acc, line) => { - const [a, b] = line.match(/\S+/g).map(Number); - acc[0].push(a); - acc[1].push(b); - return acc; - }, - [[], []] - ); - - arrayA.sort((a, b) => a - b); - arrayB.sort((a, b) => a - b); - - return arrayA.reduce((total, a, index) => { - return total + Math.abs(a - arrayB[index]); - }, 0); +const multiplyPairsTotal = (pairs) => { + return pairs.reduce((acc, pair) => acc + pair[0] * pair[1], 0); }; const main1 = () => { - console.log(getTotalDistance(inputFromAdvent)); -}; - -const getTotalSimilarity = (input) => { - const [arrayA, arrayB] = parseInput(input); - return arrayA.reduce((total, arrayAItem) => { - return ( - total + - arrayB.filter((arrayBItem) => arrayBItem === arrayAItem).length * - arrayAItem - ); - }, 0); + console.log(multiplyPairsTotal(parseInput(inputFromAdvent))); }; const main2 = () => { - console.log(getTotalSimilarity(inputFromAdvent)); + console.log(parseAndMultiplyInput(inputFromAdvent)); }; -module.exports = { - parseInput, - orderLists, - getDistance, - sumDistance, - getTotalDistance, - getTotalSimilarity, -}; +module.exports = { parseInput, multiplyPairsTotal, parseAndMultiplyInput }; // main1(); main2();",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- +2024,3,2,"--- Day 3: Mull It Over --- -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" -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! +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! -You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +For example, consider the following section of corrupted memory: -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). -For example: +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. +Your puzzle answer was 170807108. -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +--- Part Two --- -In the example list above, the pairs and distances would be as follows: +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! +There are two new instructions you'll need to handle: -Your actual left and right lists contain many location IDs. What is the total distance between your lists? - -Your puzzle answer was 2378066. - ---- Part Two --- - -Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. -Or are they? +For example: -The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. -This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. +This time, the sum of the results is 48 (2*4 + 8*5). -Here are the same example lists again: +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require('fs'); -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -For these example lists, here is the process of finding the similarity score: +function question2() { + fs.readFile('./input.txt', (err, data) => { + const memory = data.toString().replace(/\r/g, '').trimEnd(); -The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. -The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. -The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). -The fourth number, 1, also does not appear in the right list. -The fifth number, 3, appears in the right list three times; the similarity score increases by 9. -The last number, 3, appears in the right list three times; the similarity score again increases by 9. -So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). + const regex = /mul\(\d+,\d+\)|do\(\)|don't\(\)/g; -Once again consider your left and right lists. What is their similarity score?",18934359,"const fs = require('fs'); + const matches = memory.matchAll(regex); -const input = fs.readFileSync('input.txt', 'utf8'); + const instructions = []; -const lines = input.split('\n'); -const leftNumbers = []; -const rightNumbers = []; -let similarityScore = 0; + for (const match of matches) { + if (match[0].includes('mul')) { + instructions.push(match[0].slice(4, -1).split(',')); + } else { + instructions.push(match[0]); + } + } -lines.forEach((line) => { - const [left, right] = line.trim().split(/\s+/).map(Number); - leftNumbers.push(left); - rightNumbers.push(right); -}); + let addEnabled = true; + const result = instructions.reduce((acc, instr) => { + if (typeof instr !== 'string' && addEnabled) { + return (acc += instr[0] * instr[1]); + } else if (instr === 'do()') { + addEnabled = true; + return acc; + } else if (instr === ""don't()"") { + addEnabled = false; + return acc; + } else { + return acc; + } + }, 0); -for (let i = 0; i < leftNumbers.length; i++) { - let counter = rightNumbers.filter((x) => x == leftNumbers[i]).length; - similarityScore += counter * leftNumbers[i]; + console.log(result); + }); } -console.log(similarityScore);",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- - -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. - -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on 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 haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. - -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? +question2();",node:14 +2024,3,2,"--- Day 3: Mull It Over --- -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" -For example: +The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. +It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. -In the example list above, the pairs and distances would be as follows: +For example, consider the following section of corrupted memory: -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! +xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) +Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). -Your actual left and right lists contain many location IDs. What is the total distance between your lists? +Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? -Your puzzle answer was 2378066. +Your puzzle answer was 170807108. --- Part Two --- -Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. - -Or are they? - -The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. +As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. -This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. +There are two new instructions you'll need to handle: -Here are the same example lists again: +The do() instruction enables future mul instructions. +The don't() instruction disables future mul instructions. +Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -For these example lists, here is the process of finding the similarity score: +For example: -The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. -The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. -The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). -The fourth number, 1, also does not appear in the right list. -The fifth number, 3, appears in the right list three times; the similarity score increases by 9. -The last number, 3, appears in the right list three times; the similarity score again increases by 9. -So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). +xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) +This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. -Once again consider your left and right lists. What is their similarity score?",18934359,"let fs = require('fs'); -let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); +This time, the sum of the results is 48 (2*4 + 8*5). -let firstLocations = []; -let secondLocations = []; +Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require('fs'); -puzzleInput.forEach((line) => { - let parseLine = line.split(' '); - - if (parseLine[0] != '') firstLocations.push(parseLine[0]); - if (parseLine[1] != '') secondLocations.push(parseLine[1]); -}); +// Function to read and process the input data +function readInput(filePath) { + try { + const data = fs.readFileSync(filePath, 'utf8'); + return data.trim(); // Return the input string after trimming any extra whitespace + } catch (error) { + console.error('Error reading the file:', error); + return ''; + } +} -let similarityScore = 0; +// Function to process the instructions and compute the sum of valid multiplications +function calculateTotalSum(inputString) { + let totalSum = 0; + let mulEnabled = true; -firstLocations.forEach((firstLocation) => { - let occurancesInSecond = secondLocations.filter((secondLocation) => secondLocation === firstLocation).length; + const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g; + let match; - let locationSimilarityScore = occurancesInSecond > 0 ? firstLocation * occurancesInSecond : 0; + // Iterate through each instruction in the input string + while ((match = instructionRegex.exec(inputString)) !== null) { + if (match[1]) { + mulEnabled = true; // Enable mul if 'do()' is matched + } else if (match[2]) { + mulEnabled = false; // Disable mul if ""don't()"" is matched + } else if (match[3] && mulEnabled) { + // If a valid 'mul(X,Y)' is matched and mul is enabled, multiply and add to the total sum + const number1 = parseInt(match[3], 10); + const number2 = parseInt(match[4], 10); + totalSum += number1 * number2; + } + } - similarityScore += locationSimilarityScore; -}); + return totalSum; +} -console.log(similarityScore);",node:14 -2024,1,2,"--- Day 1: Historian Hysteria --- +// Main function to execute the program +function main() { + const inputString = readInput('input.txt'); + if (inputString) { + const totalSum = calculateTotalSum(inputString); + console.log(`Total sum of all multiplied numbers: ${totalSum}`); + } +} -The Chief Historian is always present for the big Christmas sleigh launch, but nobody has seen him in months! Last anyone heard, he was visiting locations that are historically significant to the North Pole; a group of Senior Historians has asked you to accompany them as they check the places they think he was most likely to visit. +main(); // Run the main function to start the process",node:14 +2024,4,1,"--- Day 4: Ceres Search --- -As each location is checked, they will mark it on their list with a star. They figure the Chief Historian must be in one of the first fifty places they'll look, so in order to save Christmas, you need to help them get fifty stars on their list before Santa takes off on December 25th. +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -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! +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -You haven't even left yet and the group of Elvish Senior Historians has already hit a problem: their list of locations to check is currently empty. Eventually, someone decides that the best place to check first would be the Chief Historian's office. +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: -Upon pouring into the office, everyone confirms that the Chief Historian is indeed nowhere to be found. Instead, the Elves discover an assortment of notes and lists of historically significant locations! This seems to be the planning the Chief Historian was doing before he left. Perhaps these notes can be used to determine which locations to search? +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -Throughout the Chief's office, the historically significant locations are listed not by name but by a unique number called the location ID. To make sure they don't miss anything, The Historians split into two groups, each searching the office and trying to create their own complete list of location IDs. +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -There's just one problem: by holding the two lists up side by side (your puzzle input), it quickly becomes clear that the lists aren't very similar. Maybe you can help The Historians reconcile their lists? +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"import fs from ""node:fs""; -For example: +const a = fs.readFileSync(""./input.txt"", ""utf8"").toString().split(""\n""); +const data = a.map((item) => item.split("""")); -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -Maybe the lists are only off by a small amount! To find out, pair up the numbers and measure how far apart they are. Pair up the smallest number in the left list with the smallest number in the right list, then the second-smallest left number with the second-smallest right number, and so on. - -Within each pair, figure out how far apart the two numbers are; you'll need to add up all of those distances. For example, if you pair up a 3 from the left list with a 7 from the right list, the distance apart is 4; if you pair up a 9 with a 3, the distance apart is 6. +const values = { + horizontalLR: 0, + horizontalRL: 0, + verticalTB: 0, + verticalBT: 0, + diagonalTLtoBR: 0, + diagonalBRtoTL: 0, + diagonalTRtoBL: 0, + diagonalBLtoTR: 0, +}; -In the example list above, the pairs and distances would be as follows: +data.forEach((item, itemIdx) => { + item.forEach((child, childIdx) => { + // Horizontal (left to right) + if (child === ""X"") { + if (data[itemIdx][childIdx + 1] === ""M"") { + if (data[itemIdx][childIdx + 2] === ""A"") { + if (data[itemIdx][childIdx + 3] === ""S"") values.horizontalLR += 1; + } + } -The smallest number in the left list is 1, and the smallest number in the right list is 3. The distance between them is 2. -The second-smallest number in the left list is 2, and the second-smallest number in the right list is another 3. The distance between them is 1. -The third-smallest number in both lists is 3, so the distance between them is 0. -The next numbers to pair up are 3 and 4, a distance of 1. -The fifth-smallest numbers in each list are 3 and 5, a distance of 2. -Finally, the largest number in the left list is 4, while the largest number in the right list is 9; these are a distance 5 apart. -To find the total distance between the left list and the right list, add up the distances between all of the pairs you found. In the example above, this is 2 + 1 + 0 + 1 + 2 + 5, a total distance of 11! + // Descending Diagonal (center to bottom right) + if (data[itemIdx + 1][childIdx + 1] === ""M"") { + if (data[itemIdx + 2][childIdx + 2] === ""A"") { + if (data[itemIdx + 3][childIdx + 3] === ""S"") + values.diagonalTLtoBR += 1; + } + } -Your actual left and right lists contain many location IDs. What is the total distance between your lists? + // Descending Vertical (center to bottom) + if (data[itemIdx + 1][childIdx] === ""M"") { + if (data[itemIdx + 2][childIdx] === ""A"") { + if (data[itemIdx + 3][childIdx] === ""S"") values.verticalTB += 1; + } + } -Your puzzle answer was 2378066. + // Descending diagonal (center to bottom left) + if (childIdx >= 3) { + if (data[itemIdx + 1][childIdx - 1] === ""M"") { + if (data[itemIdx + 2][childIdx - 2] === ""A"") { + if (data[itemIdx + 3][childIdx - 3] === ""S"") + values.diagonalTRtoBL += 1; + } + } + } ---- Part Two --- + // Horizontal (right to left) + if (childIdx >= 3) { + if (data[itemIdx][childIdx - 1] === ""M"") { + if (data[itemIdx][childIdx - 2] === ""A"") { + if (data[itemIdx][childIdx - 3] === ""S"") values.horizontalRL += 1; + } + } + } -Your analysis only confirmed what everyone feared: the two lists of location IDs are indeed very different. + // ascending diagonal (center to top left) + if (itemIdx >= 3 && childIdx >= 3) { + if (data[itemIdx - 1][childIdx - 1] === ""M"") { + if (data[itemIdx - 2][childIdx - 2] === ""A"") { + if (data[itemIdx - 3][childIdx - 3] === ""S"") + values.diagonalBRtoTL += 1; + } + } + } -Or are they? + // ascending vertical (center to top) + if (itemIdx >= 3) { + if (data[itemIdx - 1][childIdx] === ""M"") { + if (data[itemIdx - 2][childIdx] === ""A"") { + if (data[itemIdx - 3][childIdx] === ""S"") values.verticalBT += 1; + } + } + } -The Historians can't agree on which group made the mistakes or how to read most of the Chief's handwriting, but in the commotion you notice an interesting detail: a lot of location IDs appear in both lists! Maybe the other numbers aren't location IDs at all but rather misinterpreted handwriting. + // ascending diagonal (center to top right) + if (itemIdx >= 3) { + if (data[itemIdx - 1][childIdx + 1] === ""M"") { + if (data[itemIdx - 2][childIdx + 2] === ""A"") { + if (data[itemIdx - 3][childIdx + 3] === ""S"") + values.diagonalBLtoTR += 1; + } + } + } + } + }); +}); -This time, you'll need to figure out exactly how often each number from the left list appears in the right list. Calculate a total similarity score by adding up each number in the left list after multiplying it by the number of times that number appears in the right list. +console.log(values); +let count = 0; +Object.values(values).forEach((item) => { + count += item; +}); +console.log(count);",node:14 +2024,4,1,"--- Day 4: Ceres Search --- -Here are the same example lists again: +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -3 4 -4 3 -2 5 -1 3 -3 9 -3 3 -For these example lists, here is the process of finding the similarity score: +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -The first number in the left list is 3. It appears in the right list three times, so the similarity score increases by 3 * 3 = 9. -The second number in the left list is 4. It appears in the right list once, so the similarity score increases by 4 * 1 = 4. -The third number in the left list is 2. It does not appear in the right list, so the similarity score does not increase (2 * 0 = 0). -The fourth number, 1, also does not appear in the right list. -The fifth number, 3, appears in the right list three times; the similarity score increases by 9. -The last number, 3, appears in the right list three times; the similarity score again increases by 9. -So, for these example lists, the similarity score at the end of this process is 31 (9 + 4 + 0 + 0 + 9 + 9). +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: -Once again consider your left and right lists. What is their similarity score?",18934359,"const fs = require('fs'); +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -// Read the input file -const data = fs.readFileSync('input.txt', 'utf8'); +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -// Parse the input data -const lines = data.trim().split('\n'); -let leftList = []; -let rightList = []; +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"const fs = require(""fs""); +// const puzzleInput = fs.readFileSync(""./sample_input.txt"").toString().split('\n'); +const puzzleInput = fs.readFileSync(""./input.txt"").toString().split('\n'); -lines.forEach(line => { - const [left, right] = line.split(/\s+/).map(Number); - leftList.push(left); - rightList.push(right); -}); +function findWordCount(grid, word) { + const rows = grid.length; + const cols = grid[0].length; + const wordLength = word.length; + const reverseWord = word.split('').reverse().join(''); + let count = 0; -// Count occurrences of each number in the right list -const rightCount = {}; -rightList.forEach(number => { - if (rightCount[number]) { - rightCount[number]++; - } else { - rightCount[number] = 1; + function checkHorizontal(row, col) { + if (col <= cols - wordLength) { + const horizontalWord = grid[row].slice(col, col + wordLength); + if (horizontalWord === word || horizontalWord === reverseWord) { +count++; + // console.log(`Found ${word} horizontally at row ${row}, starting column ${col}`); + } + } } -}); -// Calculate the total similarity score -let totalSimilarityScore = 0; -leftList.forEach(number => { - if (rightCount[number]) { - totalSimilarityScore += number * rightCount[number]; + function checkVertical(row, col) { + if (row <= rows - wordLength) { + let verticalWord = ''; + for (let i = 0; i < wordLength; i++) { + verticalWord += grid[row + i][col]; + } + if (verticalWord === word || verticalWord === reverseWord) { + count++; + // console.log(`Found ${word} vertically at column ${col}, starting row ${row}`); + } + } } -}); - -console.log('Total Similarity Score:', totalSimilarityScore);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- - -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. - -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" - -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + function checkDiagonal(row, col) { + // Diagonal down-right + if (row <= rows - wordLength && col <= cols - wordLength) { + let diagonalWord = ''; + for (let i = 0; i < wordLength; i++) { + diagonalWord += grid[row + i][col + i]; + } + if (diagonalWord === word || diagonalWord === reverseWord) { +count++; + // console.log(`Found ${word} diagonally (down-right) starting at row ${row}, column ${col}`); + } + } -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + // Diagonal down-left + if (row <= rows - wordLength && col >= wordLength - 1) { + let diagonalWord = ''; + for (let i = 0; i < wordLength; i++) { + diagonalWord += grid[row + i][col - i]; + } + if (diagonalWord === word || diagonalWord === reverseWord) { +count++; + // console.log(`Found ${word} diagonally (down-left) starting at row ${row}, column ${col}`); + } + } + } -For example, consider the following section of corrupted memory: + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + checkHorizontal(r, c); + checkVertical(r, c); + checkDiagonal(r, c); + } + } + return count; +} -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +const wordCount = findWordCount(puzzleInput, ""XMAS""); +console.log(`Part 1: ${wordCount}`);",node:14 +2024,4,1,"--- Day 4: Ceres Search --- -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"const fs = require('fs'); +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -const input = fs.readFileSync('input.txt', 'utf8'); +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -const pattern = /mul\((\d+),(\d+)\)/g; +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: -let sum = 0; +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -let match; -while ((match = pattern.exec(input)) !== null) { - sum += match[1] * match[2]; -} +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -console.log(sum);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"const fs = require('fs'); -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +// Read the input file +const data = fs.readFileSync('input.txt', 'utf8'); +const lines = data.trim().split('\n'); +const grid = lines.map(line => line.trim().split('')); -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +const numRows = grid.length; +const numCols = grid[0].length; +const word = 'XMAS'; +let count = 0; -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +// Directions: N, NE, E, SE, S, SW, W, NW +const directions = [ + [-1, 0], // N + [-1, 1], // NE + [ 0, 1], // E + [ 1, 1], // SE + [ 1, 0], // S + [ 1, -1], // SW + [ 0, -1], // W + [-1, -1] // NW +]; -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +for (let row = 0; row < numRows; row++) { + for (let col = 0; col < numCols; col++) { + for (let [dx, dy] of directions) { + let match = true; + for (let k = 0; k < word.length; k++) { + const x = row + k * dx; + const y = col + k * dy; + if (x < 0 || x >= numRows || y < 0 || y >= numCols || grid[x][y] !== word[k]) { + match = false; + break; + } + } + if (match) { + count++; + } + } + } +} -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +console.log(`The word ""XMAS"" appears ${count} times in the grid.`);",node:14 +2024,4,1,"--- Day 4: Ceres Search --- -For example, consider the following section of corrupted memory: +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"// PART 1 +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: -const fs = require('fs'); -const path = require('path'); +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -// Resolve the file path -const filePath = path.join(__dirname, 'input.txt'); -const filePathTest1 = path.join(__dirname, 'test-1.txt'); -const filePathTest2 = path.join(__dirname, 'test-2.txt'); +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -// Read the file -function readFile(filePath) { - try { - const data = fs.readFileSync(filePath, 'utf8'); - return data; - } catch (err) { - console.error('Error reading the file:', err); - return null; - } -} +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"import fs from ""fs""; -const string = readFile(filePath); -const stringTest1 = readFile(filePathTest1); -const stringTest2 = readFile(filePathTest2); +const countXmasOccurrences = (inputFilePath) => { + const xmasMatrix = []; -// Match any group of 1-3 digits, separated by a comma, between ""mul("" and "")"" -const regex = /(?<=mul\()(\d{1,3},\d{1,3})(?=\))/g; -const arrayOfMatches = (string.match(regex)).map((el) => el.split(',').map(Number)); + try { + const text = fs.readFileSync(inputFilePath, ""utf8""); + if (!text) return 0; -const arrayMultiplied = arrayOfMatches.map((el => el.reduce((a , b) => a * b))); -const arraySummed = arrayMultiplied.reduce((a, b) => a + b); + const rows = text.trim().split(""\n""); -console.log(arraySummed); + for (const row of rows) { + xmasMatrix.push(row.split("""")); + } -// PART 2 + let xmasCounter = 0; -// Regex to find string between ""don't()"" and ""do()"" -const regexPart2 = /don't\(\).*?do\(\)/g; + for (let i = 0; i < xmasMatrix.length; i++) { + for (let j = 0; j < xmasMatrix[i].length; j++) { + const currentChar = xmasMatrix[i][j]; -// Create first array of matches -let arrayofMarchesPart2 = string.split(regexPart2).filter(Boolean); + if (xmasMatrix?.[i - 3]?.[j - 3]) { + const topLeftDiagonal = + currentChar + + xmasMatrix[i - 1][j - 1] + + xmasMatrix[i - 2][j - 2] + + xmasMatrix[i - 3][j - 3]; -// Regex to find ""don't()"" without a following ""do()"" -const regexRemoveAfterLastDont = /don't\(\)(?!.*do\(\)).*/; + if (topLeftDiagonal === ""XMAS"") xmasCounter++; + } -// Remove for each array element anything after the last ""don't()"" if no ""do()"" exists -arrayofMarchesPart2 = arrayofMarchesPart2.map(element => { - if (regexRemoveAfterLastDont.test(element)) { - return element.replace(regexRemoveAfterLastDont, ''); - } - return element; // Return the element unchanged if the condition is not met -}); + if (xmasMatrix?.[i - 3]?.[j + 3]) { + const topRightDiagonal = + currentChar + + xmasMatrix[i - 1][j + 1] + + xmasMatrix[i - 2][j + 2] + + xmasMatrix[i - 3][j + 3]; -const arrayofMarchesPart2Bis = (arrayofMarchesPart2.map((el => (el.match(regex)).map((el) => el.split(',').map(Number))))).flat(1); -const arrayMultipliedPart2 = arrayofMarchesPart2Bis.map((el => el.reduce((a , b) => a * b))); -const arraySummedPart2 = arrayMultipliedPart2.reduce((a, b) => a + b); + if (topRightDiagonal === ""XMAS"") xmasCounter++; + } -console.log(arraySummedPart2);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- + if (xmasMatrix?.[i + 3]?.[j - 3]) { + const botLeftDiagonal = + currentChar + + xmasMatrix[i + 1][j - 1] + + xmasMatrix[i + 2][j - 2] + + xmasMatrix[i + 3][j - 3]; -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. + if (botLeftDiagonal === ""XMAS"") xmasCounter++; + } -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + if (xmasMatrix?.[i + 3]?.[j + 3]) { + const botRightDiagonal = + currentChar + + xmasMatrix[i + 1][j + 1] + + xmasMatrix[i + 2][j + 2] + + xmasMatrix[i + 3][j + 3]; -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + if (botRightDiagonal === ""XMAS"") xmasCounter++; + } -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + if (xmasMatrix[i]?.[j - 3]) { + const left = + currentChar + + xmasMatrix[i][j - 1] + + xmasMatrix[i][j - 2] + + xmasMatrix[i][j - 3]; -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + if (left === ""XMAS"") xmasCounter++; + } -For example, consider the following section of corrupted memory: + if (xmasMatrix[i]?.[j + 3]) { + const right = + currentChar + + xmasMatrix[i][j + 1] + + xmasMatrix[i][j + 2] + + xmasMatrix[i][j + 3]; -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + if (right === ""XMAS"") xmasCounter++; + } -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"let fs = require('fs'); -let puzzleInput = fs.readFileSync('input.txt').toString(); + if (xmasMatrix?.[i - 3]?.[j]) { + const top = + currentChar + + xmasMatrix[i - 1][j] + + xmasMatrix[i - 2][j] + + xmasMatrix[i - 3][j]; -let mul = (a, b) => a * b; + if (top === ""XMAS"") xmasCounter++; + } -let regexp = /mul\([0-9]{1,3},[0-9]{1,3}\)/g; -let multiplications = puzzleInput.match(regexp); + if (xmasMatrix?.[i + 3]?.[j]) { + const bot = + currentChar + + xmasMatrix[i + 1][j] + + xmasMatrix[i + 2][j] + + xmasMatrix[i + 3][j]; -let total = 0; + if (bot === ""XMAS"") xmasCounter++; + } + } + } + return xmasCounter; + } catch (err) { + console.error(err); + } +}; -multiplications.forEach((thisMul) => { - let mulValue = eval(thisMul); +const totalXmasOccurrences = countXmasOccurrences(""./puzzle-input.txt""); +console.log(totalXmasOccurrences);",node:14 +2024,4,1,"--- Day 4: Ceres Search --- - total += mulValue; -}) +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -console.log(total);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- - -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. - -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" - -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -For example, consider the following section of corrupted memory: +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"let fs = require('fs'); +let rows = fs.readFileSync('input.txt').toString().split(""\n""); -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"const fs = require(""fs""); +// We need a Width and a Height - we will assume it is a rectangular wordsearch and that all rows are the same length +const WIDTH = rows[0].length; +const HEIGHT = rows.length; -let buffer, input, rows; +const DIRECTIONS = [ + [1, 0], // East + [1, 1], // South East + [0, 1], // South + [-1, 1], // South West + [-1, 0], // West + [-1, -1], // North West + [0, -1], // North + [1, -1], // North East +]; -try { - buffer = fs.readFileSync(__dirname + ""/input.txt"", ""utf8""); -} catch (e) { - throw e; -} +const SEARCH = 'XMAS'; -input = buffer.toString(); -rows = input.split(""\n""); +// Keep a running total of how many times we have found the Search Word +let runningTotal = 0; -const multiply_sum = rows.reduce((accumulator, row) => { - if (row === """") return accumulator; // Empty row check, skip - let sum = 0; - let results; +rows.forEach((row, rowIndex) => { + if (row.length > 0) { + [...row].forEach((letter, colIndex) => { + if (letter === SEARCH[0]) { + DIRECTIONS.forEach((direction) => { + for (let i = 1; i <= SEARCH.length - 1; i++) { + let coordY = rowIndex + (direction[0] * i); + let coordX = colIndex + (direction[1] * i); + if (coordY < HEIGHT && coordY >= 0 && coordX < WIDTH && coordX >= 0) { + if (rows[coordY][coordX] === SEARCH[i]) { + if (i === SEARCH.length - 1) { + runningTotal++; + break; + } + } else { + break; + } + } + } + }); + } + }); + } +}); - // Match mul(x,y) from row as string - const regex = /mul\((\d+)\,(\d+)\)/g; - while ((results = regex.exec(row)) !== null) { - // Match numbers from mul(x,y) - sum += Number(results[1]) * Number(results[2]); - // console.log(`Found ${results[1]} x ${results[2]} at ${results.index}.`); - } +console.log(runningTotal);",node:14 +2024,4,2,"--- Day 4: Ceres Search --- - return accumulator + sum; -}, 0); +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -console.log({ multiply_sum });",node:14 -2024,3,1,"--- Day 3: Mull It Over --- +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +Your puzzle answer was 2434. -For example, consider the following section of corrupted memory: +--- Part Two --- -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +The Elf looks quizzically at you. Did you misunderstand the assignment? -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"const fs = require('fs'); +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: -// Read the input file -const data = fs.readFileSync('input.txt', 'utf8'); +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. -const lines = data.trim().split('\n'); -let totalSum = 0; +Here's the same example from before, but this time all of the X-MASes have been kept instead: -//Constructs regex to match criteria: -//mul(number1, number2) where number1 and number2 are 1-3 digit numbers -const regex = /mul\((\d{1,3}),(\d{1,3})\)/g; +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. -lines.forEach(line => { - let match; - //regex.exec finds all the matches - while ((match = regex.exec(line)) !== null) { - //Parses the string to return an integer as a base10 (standard numeric output) - const number1 = parseInt(match[1], 10); - const number2 = parseInt(match[2], 10); - totalSum += number1 * number2; - } -}); -console.log(`Total sum of all multiplied numbers: ${totalSum}`);",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"import fs from ""node:fs""; -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +const a = fs.readFileSync(""./input.txt"", ""utf8"").toString().split(""\n""); +const data = a.map((item) => item.split("""")); -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +let count = 0; -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +data.forEach((_, vertIdx) => { + data[vertIdx].forEach((_, horzIdx) => { + if (vertIdx >= 1 && horzIdx >= 1) { + if (data[vertIdx][horzIdx] === ""A"") { + if ( + data[vertIdx - 1][horzIdx - 1] === ""M"" && + data[vertIdx - 1][horzIdx + 1] === ""S"" && + data[vertIdx + 1][horzIdx - 1] === ""M"" && + data[vertIdx + 1][horzIdx + 1] === ""S"" + ) { + count += 1; + } -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + if ( + data[vertIdx - 1][horzIdx - 1] === ""S"" && + data[vertIdx - 1][horzIdx + 1] === ""S"" && + data[vertIdx + 1][horzIdx - 1] === ""M"" && + data[vertIdx + 1][horzIdx + 1] === ""M"" + ) { + count += 1; + } -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + if ( + data[vertIdx - 1][horzIdx - 1] === ""M"" && + data[vertIdx - 1][horzIdx + 1] === ""M"" && + data[vertIdx + 1][horzIdx - 1] === ""S"" && + data[vertIdx + 1][horzIdx + 1] === ""S"" + ) { + count += 1; + } -For example, consider the following section of corrupted memory: + if ( + data[vertIdx - 1][horzIdx - 1] === ""S"" && + data[vertIdx - 1][horzIdx + 1] === ""M"" && + data[vertIdx + 1][horzIdx - 1] === ""S"" && + data[vertIdx + 1][horzIdx + 1] === ""M"" + ) { + count += 1; + } + } + } + }); +}); +console.log(count);",node:14 +2024,4,2,"--- Day 4: Ceres Search --- -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -Your puzzle answer was 170807108. +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: ---- Part Two --- +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. - -There are two new instructions you'll need to handle: - -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. - -For example: +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? -This time, the sum of the results is 48 (2*4 + 8*5). +Your puzzle answer was 2434. -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"let fs = require('fs'); -let puzzleInput = fs.readFileSync('input.txt').toString(); +--- Part Two --- -let mul = (a, b) => a * b; +The Elf looks quizzically at you. Did you misunderstand the assignment? -let regEx = /do\(\)|don\'t\(\)|mul\([0-9]{1,3},[0-9]{1,3}\)/g; -let parts = puzzleInput.match(regEx); +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: -let doing = true; -let total = 0; +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. -parts.forEach((part) => { - if (doing && part.substring(0, 3) == 'mul') { - let value = eval(part); - total += value; - } +Here's the same example from before, but this time all of the X-MASes have been kept instead: - if (part.substring(0, 3) == 'do(') doing = true; - if (part.substring(0, 3) == 'don') doing = false; -}); +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. -console.log(total);",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"const fs = require(""fs""); +const filename = ""input.txt""; -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +var buffer, input, rows; -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +try { + buffer = fs.readFileSync(__dirname + ""/"" + filename, ""utf8""); +} catch (e) { + throw e; +} -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +input = buffer.toString(); +rows = input.split(""\n"").map(el => el.split("""")); -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +function find_xmas(letter, i, j) { + let total = 0; + if (letter !== 'A') return total; // This aint it fam -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + // If the coords exists, check for the letter + // M ? S + // ? A ? + // M ? S + if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""M"") { + if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""S"") { + if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""M"") { + if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""S"") { + total++; + } + } + } + } -For example, consider the following section of corrupted memory: + // M ? M + // ? A ? + // S ? S + if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""M"") { + if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""M"") { + if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""S"") { + if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""S"") { + total++; + } + } + } + } -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + // S ? S + // ? A ? + // M ? M + if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""S"") { + if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""S"") { + if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""M"") { + if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""M"") { + total++; + } + } + } + } -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? + // S ? M + // ? A ? + // S ? M + if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""S"") { + if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""M"") { + if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""S"") { + if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""M"") { + total++; + } + } + } + } -Your puzzle answer was 170807108. ---- Part Two --- + return total; +} -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. +let found_xmass = 0; -There are two new instructions you'll need to handle: +for (let i = 0; i < rows.length; i++) { + for (let j = 0; j < rows[i].length; j++) { + found_xmass += find_xmas(rows[i][j], i, j); + } +} -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. +console.log({ found_xmass });",node:14 +2024,4,2,"--- Day 4: Ceres Search --- -For example: +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -This time, the sum of the results is 48 (2*4 + 8*5). +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require('fs'); +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -// Read the input file -const data = fs.readFileSync('input.txt', 'utf8'); -const inputString = data.trim(); +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -let totalSum = 0; -let mulEnabled = true; +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? -const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g; +Your puzzle answer was 2434. -let match; -while ((match = instructionRegex.exec(inputString)) !== null) { - if (match[1]) { - // Matched 'do()' - mulEnabled = true; - } else if (match[2]) { - // Matched ""don't()"" - mulEnabled = false; - } else if (match[3] && mulEnabled) { - // Matched 'mul(X,Y)' and mul is enabled - const number1 = parseInt(match[3], 10); - const number2 = parseInt(match[4], 10); - totalSum += number1 * number2; - } -} +--- Part Two --- -console.log(`Total sum of all multiplied numbers: ${totalSum}`);",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +The Elf looks quizzically at you. Did you misunderstand the assignment? -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +Here's the same example from before, but this time all of the X-MASes have been kept instead: -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"const fs = require('fs'); -For example, consider the following section of corrupted memory: +// Function to read the input file and split it into rows +function readInput(filePath) { + try { + const data = fs.readFileSync(filePath, 'utf-8'); + return data.split(""\n"").filter(row => row.length > 0); // Filter out any empty rows + } catch (error) { + console.error('Error reading the file:', error); + return []; + } +} -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +// Function to check if an ""X-MAS"" pattern is found at a given position in the grid +function isXMASPattern(rows, rowIndex, colIndex, WIDTH, HEIGHT) { + // Check if we're within bounds and the letter at the center is 'A' + if (rowIndex > 0 && rowIndex < HEIGHT - 1 && colIndex > 0 && colIndex < WIDTH - 1 && rows[rowIndex][colIndex] === 'A') { + return ( + // Check for diagonals forming 'X-MAS' in both directions + ( + rows[rowIndex + 1][colIndex + 1] === 'M' && rows[rowIndex - 1][colIndex - 1] === 'S' || + rows[rowIndex + 1][colIndex + 1] === 'S' && rows[rowIndex - 1][colIndex - 1] === 'M' + ) && + ( + rows[rowIndex + 1][colIndex - 1] === 'M' && rows[rowIndex - 1][colIndex + 1] === 'S' || + rows[rowIndex + 1][colIndex - 1] === 'S' && rows[rowIndex - 1][colIndex + 1] === 'M' + ) + ); + } + return false; +} -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? +// Function to count occurrences of the ""X-MAS"" pattern in the grid +function countXMASPatterns(rows, WIDTH, HEIGHT) { + let runningTotal = 0; -Your puzzle answer was 170807108. + // Loop over each row and column to check for ""X-MAS"" patterns + rows.forEach((row, rowIndex) => { + [...row].forEach((letter, colIndex) => { + if (isXMASPattern(rows, rowIndex, colIndex, WIDTH, HEIGHT)) { + runningTotal++; + } + }); + }); ---- Part Two --- + return runningTotal; +} -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. +// Main function to orchestrate the entire process +function main() { + const rows = readInput('input.txt'); + if (rows.length === 0) return; -There are two new instructions you'll need to handle: + const WIDTH = rows[0].length; + const HEIGHT = rows.length; -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. + // Count the occurrences of ""X-MAS"" patterns + const totalPatterns = countXMASPatterns(rows, WIDTH, HEIGHT); -For example: + // Output the result + console.log(totalPatterns); +} -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. +main(); // Run the main function",node:14 +2024,4,2,"--- Day 4: Ceres Search --- -This time, the sum of the results is 48 (2*4 + 8*5). +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require(""fs""); -const path = require(""path""); -const fileTxt = fs.readFileSync(path.join(__dirname, ""input.txt"")); -const inputFromAdvent = fileTxt.toString(); +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -const parseInput = (input) => { - // want to take only between () and comma inside after mul. Eg mul(2,4) 2,4 - const regex = /mul\((\d+),(\d+)\)/g; - const matches = input.match(regex); - return matches.map((match) => match.slice(4, -1).split("","").map(Number)); -}; +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: -const parseAndMultiplyInput = (input) => { - return input - .split(""do()"") // split into chunks - .map((chunk) => chunk.split(""don't()"")[0]) // remove don't() - .map((s) => [...s.matchAll(/mul\((\d+),(\d+)\)/g)]) // find all mul pairs - .flatMap((m) => m.map((m) => m[1] * m[2])) // multiply pairs - .reduce((acc, curr) => acc + curr, 0); // sum up -}; +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -const multiplyPairsTotal = (pairs) => { - return pairs.reduce((acc, pair) => acc + pair[0] * pair[1], 0); -}; +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -const main1 = () => { - console.log(multiplyPairsTotal(parseInput(inputFromAdvent))); -}; +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? -const main2 = () => { - console.log(parseAndMultiplyInput(inputFromAdvent)); -}; +Your puzzle answer was 2434. -module.exports = { parseInput, multiplyPairsTotal, parseAndMultiplyInput }; +--- Part Two --- -// main1(); -main2();",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +The Elf looks quizzically at you. Did you misunderstand the assignment? -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +Here's the same example from before, but this time all of the X-MASes have been kept instead: -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"let fs = require('fs'); +let rows = fs.readFileSync('input.txt').toString().split(""\n""); -For example, consider the following section of corrupted memory: +// We need a Width and a Height - we will assume it is a rectangular wordsearch and that all rows are the same length +const WIDTH = rows[0].length; +const HEIGHT = rows.length; -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +// Keep a running total of how many times we have found the Search Word +let runningTotal = 0; -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? +rows.forEach((row, rowIndex) => { + if (row.length > 0) { + [...row].forEach((letter, colIndex) => { + if (letter === 'A') { + if ( + rowIndex > 0 && rowIndex < HEIGHT - 1 && + colIndex > 0 && colIndex < WIDTH - 1 && + ( + (rows[rowIndex + 1][colIndex + 1] === 'M' && rows[rowIndex - 1][colIndex - 1] === 'S') || + (rows[rowIndex + 1][colIndex + 1] === 'S' && rows[rowIndex - 1][colIndex - 1] === 'M') + ) && + ( + (rows[rowIndex + 1][colIndex - 1] === 'M' && rows[rowIndex - 1][colIndex + 1] === 'S') || + (rows[rowIndex + 1][colIndex - 1] === 'S' && rows[rowIndex - 1][colIndex + 1] === 'M') + ) + ) { + runningTotal++; + } + } + }); + } +}); -Your puzzle answer was 170807108. +console.log(runningTotal);",node:14 +2024,4,2,"--- Day 4: Ceres Search --- ---- Part Two --- +""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. +As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. -There are two new instructions you'll need to handle: +This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. +..X... +.SAMX. +.A..A. +XMAS.S +.X.... +The actual word search will be full of letters instead. For example: -For example: +MMMSXXMASM +MSAMXMSMSA +AMXSXMAAMM +MSAMASMSMX +XMASAMXAMM +XXAMMXXAMA +SMSMSASXSS +SAXAMASAAA +MAMMMXMMMM +MXMXAXMASX +In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. +....XXMAS. +.SAMXMS... +...S..A... +..A.A.MS.X +XMASAMX.MM +X.....XA.A +S.S.S.S.SS +.A.A.A.A.A +..M.M.M.MM +.X.X.XMASX +Take a look at the little Elf's word search. How many times does XMAS appear? -This time, the sum of the results is 48 (2*4 + 8*5). +Your puzzle answer was 2434. -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require('fs'); +--- Part Two --- -function question2() { - fs.readFile('./input.txt', (err, data) => { - const memory = data.toString().replace(/\r/g, '').trimEnd(); +The Elf looks quizzically at you. Did you misunderstand the assignment? - const regex = /mul\(\d+,\d+\)|do\(\)|don't\(\)/g; +Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: - const matches = memory.matchAll(regex); +M.S +.A. +M.S +Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. - const instructions = []; +Here's the same example from before, but this time all of the X-MASes have been kept instead: - for (const match of matches) { - if (match[0].includes('mul')) { - instructions.push(match[0].slice(4, -1).split(',')); - } else { - instructions.push(match[0]); - } - } +.M.S...... +..A..MSMS. +.M.S.MAA.. +..A.ASMSM. +.M.S.M.... +.......... +S.S.S.S.S. +.A.A.A.A.. +M.M.M.M.M. +.......... +In this example, an X-MAS appears 9 times. - let addEnabled = true; - const result = instructions.reduce((acc, instr) => { - if (typeof instr !== 'string' && addEnabled) { - return (acc += instr[0] * instr[1]); - } else if (instr === 'do()') { - addEnabled = true; - return acc; - } else if (instr === ""don't()"") { - addEnabled = false; - return acc; - } else { - return acc; - } - }, 0); +Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"const fs = require('fs'); - console.log(result); - }); -} +// Read the input file and create the grid +const data = fs.readFileSync('input.txt', 'utf8'); +const lines = data.trim().split('\n'); +const grid = lines.map(line => line.trim().split('')); -question2();",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +const numRows = grid.length; +const numCols = grid[0].length; +let count = 0; -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +// Directions for diagonals +const dir1 = [-1, -1]; // Top-left to bottom-right +const dir2 = [-1, 1]; // Top-right to bottom-left -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +for (let row = 0; row < numRows; row++) { + for (let col = 0; col < numCols; col++) { + if (grid[row][col] === 'A') { + let valid1 = false; + let valid2 = false; + + // Check diagonal from top-left to bottom-right + // Check diagonal from top-left to bottom-right +if ( + row - 1 >= 0 && col - 1 >= 0 && + row + 1 < numRows && col + 1 < numCols && + ( + (grid[row - 1][col - 1] === 'M' && grid[row + 1][col + 1] === 'S') || + (grid[row - 1][col - 1] === 'S' && grid[row + 1][col + 1] === 'M') + ) + ) { + valid1 = true; + } + + // Check diagonal from top-right to bottom-left + if ( + row - 1 >= 0 && col + 1 < numCols && + row + 1 < numRows && col - 1 >= 0 && + ( + (grid[row - 1][col + 1] === 'M' && grid[row + 1][col - 1] === 'S') || + (grid[row - 1][col + 1] === 'S' && grid[row + 1][col - 1] === 'M') + ) + ) { + valid2 = true; + } + + // If both diagonals form 'MAS' or 'SAM', increment count + if (valid1 && valid2) { + count++; + } + } + } + } + + console.log(`Number of X-MAS patterns found: ${count}`);",node:14 +2024,6,1,"--- Day 6: Guard Gallivant --- -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? -For example, consider the following section of corrupted memory: +You start by making a map (your puzzle input) of the situation. For example: -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -Your puzzle answer was 170807108. +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): ---- Part Two --- +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: -There are two new instructions you'll need to handle: +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: -For example: +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); -This time, the sum of the results is 48 (2*4 + 8*5). +// Read the input file +const input = fs.readFileSync('input.txt', 'utf8').trim(); +const map = input.split('\n'); -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require('fs'); +// Directions: Up, Right, Down, Left +const directions = ['^', '>', 'v', '<']; +let direction = ''; +let position = { x: 0, y: 0 }; -// Function to read and process the input data -function readInput(filePath) { - try { - const data = fs.readFileSync(filePath, 'utf8'); - return data.trim(); // Return the input string after trimming any extra whitespace - } catch (error) { - console.error('Error reading the file:', error); - return ''; +// Parse the map to find the initial position and direction of the guard +for (let y = 0; y < map.length; y++) { + for (let x = 0; x < map[y].length; x++) { + if (directions.includes(map[y][x])) { + position = { x, y }; + direction = map[y][x]; + break; + } } + if (direction) break; } -// Function to process the instructions and compute the sum of valid multiplications -function calculateTotalSum(inputString) { - let totalSum = 0; - let mulEnabled = true; +// Directions mapping for movement +const movement = { + '^': { dx: 0, dy: -1 }, // Up + '>': { dx: 1, dy: 0 }, // Right + 'v': { dx: 0, dy: 1 }, // Down + '<': { dx: -1, dy: 0 }, // Left +}; - const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g; - let match; +// Set to track the visited positions +const visited = new Set(); +visited.add(`${position.x},${position.y}`); - // Iterate through each instruction in the input string - while ((match = instructionRegex.exec(inputString)) !== null) { - if (match[1]) { - mulEnabled = true; // Enable mul if 'do()' is matched - } else if (match[2]) { - mulEnabled = false; // Disable mul if ""don't()"" is matched - } else if (match[3] && mulEnabled) { - // If a valid 'mul(X,Y)' is matched and mul is enabled, multiply and add to the total sum - const number1 = parseInt(match[3], 10); - const number2 = parseInt(match[4], 10); - totalSum += number1 * number2; - } - } +// Function to turn right +const turnRight = (currentDirection) => { + const idx = directions.indexOf(currentDirection); + return directions[(idx + 1) % 4]; +}; - return totalSum; -} +let guardRunning = true; -// Main function to execute the program -function main() { - const inputString = readInput('input.txt'); - if (inputString) { - const totalSum = calculateTotalSum(inputString); - console.log(`Total sum of all multiplied numbers: ${totalSum}`); +while (guardRunning) { + // Calculate the next position + const nextX = position.x + movement[direction].dx; + const nextY = position.y + movement[direction].dy; + + // Check if the next position is outside the map + if ( + nextX < 0 || + nextX >= map[0].length || + nextY < 0 || + nextY >= map.length + ) { + guardRunning = false; // Guard leaves the map + } else { + // Check if the next position is an obstacle + if (map[nextY][nextX] === '#') { + // Turn right + direction = turnRight(direction); + } else { + // Move forward + position.x = nextX; + position.y = nextY; + visited.add(`${position.x},${position.y}`); + } } } -main(); // Run the main function to start the process",node:14 -2024,3,1,"--- Day 3: Mull It Over --- - -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. - -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" - -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! - -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +console.log(visited.size); // The number of distinct positions visited",node:14 +2024,6,1,"--- Day 6: Guard Gallivant --- -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. -For example, consider the following section of corrupted memory: +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"// PART 1 +You start by making a map (your puzzle input) of the situation. For example: -const fs = require('fs'); -const path = require('path'); +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -// Resolve the file path -const filePath = path.join(__dirname, 'input.txt'); -const filePathTest1 = path.join(__dirname, 'test-1.txt'); -const filePathTest2 = path.join(__dirname, 'test-2.txt'); +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -// Read the file -function readFile(filePath) { - try { - const data = fs.readFileSync(filePath, 'utf8'); - return data; - } catch (err) { - console.error('Error reading the file:', err); - return null; - } -} +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): -const string = readFile(filePath); -const stringTest1 = readFile(filePathTest1); -const stringTest2 = readFile(filePathTest2); +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -// Match any group of 1-3 digits, separated by a comma, between ""mul("" and "")"" -const regex = /(?<=mul\()(\d{1,3},\d{1,3})(?=\))/g; -const arrayOfMatches = (string.match(regex)).map((el) => el.split(',').map(Number)); +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: -const arrayMultiplied = arrayOfMatches.map((el => el.reduce((a , b) => a * b))); -const arraySummed = arrayMultiplied.reduce((a, b) => a + b); +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -console.log(arraySummed); +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: -// PART 2 +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -// Regex to find string between ""don't()"" and ""do()"" -const regexPart2 = /don't\(\).*?do\(\)/g; +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require(""fs""); +const inputText = ""./input.txt""; -// Create first array of matches -let arrayofMarchesPart2 = string.split(regexPart2).filter(Boolean); +fs.readFile(inputText, ""utf8"", (err, data) => { + if (err) { + console.error('Error reading file:', err); + return; + } -// Regex to find ""don't()"" without a following ""do()"" -const regexRemoveAfterLastDont = /don't\(\)(?!.*do\(\)).*/; + const rows = data.split(""\n"").map(row => row.split("""")); + let guardLocation = rows + .map((row, i) => { + if (row.includes(""^"")) { + // Turn guard icon into a normal traversable space + const guardLocation = row.indexOf(""^"") + rows[i][guardLocation] = "".""; + return { x: i, y: guardLocation } + } + }) + .filter(row => row)[0]; -// Remove for each array element anything after the last ""don't()"" if no ""do()"" exists -arrayofMarchesPart2 = arrayofMarchesPart2.map(element => { - if (regexRemoveAfterLastDont.test(element)) { - return element.replace(regexRemoveAfterLastDont, ''); - } - return element; // Return the element unchanged if the condition is not met + console.log(part1(rows, guardLocation)); + console.log(part2(rows, guardLocation)); }); -const arrayofMarchesPart2Bis = (arrayofMarchesPart2.map((el => (el.match(regex)).map((el) => el.split(',').map(Number))))).flat(1); -const arrayMultipliedPart2 = arrayofMarchesPart2Bis.map((el => el.reduce((a , b) => a * b))); -const arraySummedPart2 = arrayMultipliedPart2.reduce((a, b) => a + b); +const directions = { + ""up"": { dx: -1, dy: 0, next: ""right"" }, + ""right"": { dx: 0, dy: 1, next: ""down"" }, + ""down"": { dx: 1, dy: 0, next: ""left"" }, + ""left"": { dx: 0, dy: -1, next: ""up"" }, +}; -console.log(arraySummedPart2);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- +// Get all places guard visits +const getPlacesVisited = (rows, guardLocation) => { + let placesVisited = new Set(); + let guardDirection = ""up""; + let nextGuardLocation; + while (nextGuardLocation !== null) { + const { x, y } = guardLocation; + const { dx, dy} = directions[guardDirection]; + let possibleNextCoords = { x: x + dx, y: y + dy }; + + // Check if in bounds + if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1|| + possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) { + placesVisited.add(`${x}, ${y}`); + nextGuardLocation = null; + break; + } -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. + if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ""."") { + guardDirection = directions[guardDirection].next; + } else { + guardLocation = possibleNextCoords; + nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y]; + placesVisited.add(`${x}, ${y}`); + } + } + return placesVisited; +} -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +const checkInfiniteLoop = (rows, guardLocation) => { + const placesVisited = new Set(); + let guardDirection = ""up""; + let nextGuardLocation; -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + while (true) { + const { x, y } = guardLocation; + const { dx, dy} = directions[guardDirection]; + let possibleNextCoords = { x: x + dx, y: y + dy }; + + // Check if guard has been here before, and in the same direction, indicating an infinite loop + const currentPosition = `${x}, ${y}, ${guardDirection}` + if (placesVisited.has(currentPosition)) { + return true; + } + placesVisited.add(currentPosition); -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + // Check if in bounds + if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1|| + possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) { + return false; + } -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ""."") { + guardDirection = directions[guardDirection].next; + } else { + guardLocation = possibleNextCoords; + nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y]; + } + } +} -For example, consider the following section of corrupted memory: +const part1 = (rows, guardLocation) => getPlacesVisited(rows, guardLocation).size; -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +const part2 = (rows, guardLocation) => { + // All the places the guard would normally visit (minus starting location) + const placesVisited = [...getPlacesVisited(rows, guardLocation)].slice(1); + let infiniteLoops = 0; + + for (let i = 0; i < placesVisited.length; i++) { + const [ obstacleX, obstacleY ] = placesVisited[i].split("", "").map(Number); + + // Temporarily change normal tile to obstacle + rows[obstacleX][obstacleY] = ""#""; + + if (checkInfiniteLoop(rows, guardLocation)) infiniteLoops++; -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"const fs = require('fs'); + // Return obstacle to normal tile + rows[obstacleX][obstacleY] = "".""; + } + return infiniteLoops; +}",node:14 +2024,6,1,"--- Day 6: Guard Gallivant --- -const input = fs.readFileSync('input.txt', 'utf8'); +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. -const pattern = /mul\((\d+),(\d+)\)/g; +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -let sum = 0; +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? -let match; -while ((match = pattern.exec(input)) !== null) { - sum += match[1] * match[2]; -} +You start by making a map (your puzzle input) of the situation. For example: -console.log(sum);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- - -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. - -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -For example, consider the following section of corrupted memory: +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"const fs = require(""fs""); +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: -let buffer, input, rows; +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -try { - buffer = fs.readFileSync(__dirname + ""/input.txt"", ""utf8""); -} catch (e) { - throw e; -} +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); -input = buffer.toString(); -rows = input.split(""\n""); +// Directions: Up, Right, Down, Left +const DIRECTIONS = ['^', '>', 'v', '<']; -const multiply_sum = rows.reduce((accumulator, row) => { - if (row === """") return accumulator; // Empty row check, skip - let sum = 0; - let results; +// Movement offsets for each direction +const MOVEMENT = { + '^': { dx: 0, dy: -1 }, // Up + '>': { dx: 1, dy: 0 }, // Right + 'v': { dx: 0, dy: 1 }, // Down + '<': { dx: -1, dy: 0 }, // Left +}; - // Match mul(x,y) from row as string - const regex = /mul\((\d+)\,(\d+)\)/g; - while ((results = regex.exec(row)) !== null) { - // Match numbers from mul(x,y) - sum += Number(results[1]) * Number(results[2]); - // console.log(`Found ${results[1]} x ${results[2]} at ${results.index}.`); +// Function to find the guard's starting position and direction +const findGuard = (map) => { + for (let y = 0; y < map.length; y++) { + for (let x = 0; x < map[y].length; x++) { + if (DIRECTIONS.includes(map[y][x])) { + return { x, y, direction: map[y][x] }; + } + } } + throw new Error('Guard not found on the map!'); +}; - return accumulator + sum; -}, 0); +// Function to turn the guard 90 degrees to the right +const turnRight = (direction) => { + const currentIndex = DIRECTIONS.indexOf(direction); + return DIRECTIONS[(currentIndex + 1) % 4]; +}; -console.log({ multiply_sum });",node:14 -2024,3,1,"--- Day 3: Mull It Over --- +// Function to get the next position based on the current position and direction +const getNextPosition = (x, y, direction) => { + const { dx, dy } = MOVEMENT[direction]; + return { x: x + dx, y: y + dy }; +}; -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +// Function to check if a position is within the map boundaries +const isWithinBounds = (x, y, map) => { + return x >= 0 && x < map[0].length && y >= 0 && y < map.length; +}; -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +// Function to check if a position is an obstacle +const isObstacle = (x, y, map) => { + return map[y][x] === '#'; +}; -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +// Function to simulate the guard's movement +const simulateGuardMovement = (map) => { + const { x, y, direction } = findGuard(map); + let currentDirection = direction; + let currentPosition = { x, y }; -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + const visited = new Set(); + visited.add(`${currentPosition.x},${currentPosition.y}`); -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + while (true) { + const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); -For example, consider the following section of corrupted memory: + // Check if the guard is leaving the map + if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { + break; + } -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + // Check if the next position is an obstacle + if (isObstacle(nextPosition.x, nextPosition.y, map)) { + currentDirection = turnRight(currentDirection); // Turn right + } else { + currentPosition = nextPosition; // Move forward + visited.add(`${currentPosition.x},${currentPosition.y}`); + } + } -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"const fs = require('fs'); + return visited.size; +}; // Read the input file -const data = fs.readFileSync('input.txt', 'utf8'); - -const lines = data.trim().split('\n'); -let totalSum = 0; - -//Constructs regex to match criteria: -//mul(number1, number2) where number1 and number2 are 1-3 digit numbers -const regex = /mul\((\d{1,3}),(\d{1,3})\)/g; - -lines.forEach(line => { - let match; - //regex.exec finds all the matches - while ((match = regex.exec(line)) !== null) { - //Parses the string to return an integer as a base10 (standard numeric output) - const number1 = parseInt(match[1], 10); - const number2 = parseInt(match[2], 10); - totalSum += number1 * number2; - } -}); -console.log(`Total sum of all multiplied numbers: ${totalSum}`);",node:14 -2024,3,1,"--- Day 3: Mull It Over --- - -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +const input = fs.readFileSync('input.txt', 'utf8').trim(); +const map = input.split('\n'); -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +// Simulate the guard's movement and print the result +const distinctPositions = simulateGuardMovement(map); +console.log(`Number of distinct positions visited: ${distinctPositions}`);",node:14 +2024,6,1,"--- Day 6: Guard Gallivant --- -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? -For example, consider the following section of corrupted memory: +You start by making a map (your puzzle input) of the situation. For example: -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications?",170807108,"let fs = require('fs'); -let puzzleInput = fs.readFileSync('input.txt').toString(); +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -let mul = (a, b) => a * b; +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): -let regexp = /mul\([0-9]{1,3},[0-9]{1,3}\)/g; -let multiplications = puzzleInput.match(regexp); +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -let total = 0; +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: -multiplications.forEach((thisMul) => { - let mulValue = eval(thisMul); - - total += mulValue; -}) - -console.log(total);",node:14 -2024,3,2,"--- Day 3: Mull It Over --- - -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. - -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); -For example, consider the following section of corrupted memory: +// Class to represent the Guard +class Guard { + constructor(x, y, direction) { + this.x = x; + this.y = y; + this.direction = direction; + this.directions = ['^', '>', 'v', '<']; // Up, Right, Down, Left + this.movement = { + '^': { dx: 0, dy: -1 }, // Up + '>': { dx: 1, dy: 0 }, // Right + 'v': { dx: 0, dy: 1 }, // Down + '<': { dx: -1, dy: 0 }, // Left + }; + } -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + // Turn the guard 90 degrees to the right + turnRight() { + const currentIndex = this.directions.indexOf(this.direction); + this.direction = this.directions[(currentIndex + 1) % 4]; + } -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? + // Move the guard forward in the current direction + moveForward() { + const { dx, dy } = this.movement[this.direction]; + this.x += dx; + this.y += dy; + } -Your puzzle answer was 170807108. + // Get the next position without actually moving + getNextPosition() { + const { dx, dy } = this.movement[this.direction]; + return { x: this.x + dx, y: this.y + dy }; + } +} ---- Part Two --- +// Class to represent the Map +class Map { + constructor(grid) { + this.grid = grid; + this.width = grid[0].length; + this.height = grid.length; + } -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. + // Check if a position is within the map boundaries + isWithinBounds(x, y) { + return x >= 0 && x < this.width && y >= 0 && y < this.height; + } -There are two new instructions you'll need to handle: + // Check if a position is an obstacle + isObstacle(x, y) { + return this.grid[y][x] === '#'; + } -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. + // Find the guard's starting position and direction + findGuard() { + for (let y = 0; y < this.height; y++) { + for (let x = 0; x < this.width; x++) { + if ('^>v<'.includes(this.grid[y][x])) { + return { x, y, direction: this.grid[y][x] }; + } + } + } + throw new Error('Guard not found on the map!'); + } +} -For example: +// Main function to simulate the guard's movement +function simulateGuardMovement(map) { + const guardMap = new Map(map); + const { x, y, direction } = guardMap.findGuard(); + const guard = new Guard(x, y, direction); -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. + const visited = new Set(); + visited.add(`${guard.x},${guard.y}`); -This time, the sum of the results is 48 (2*4 + 8*5). + while (true) { + const nextPosition = guard.getNextPosition(); -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require(""fs""); -const path = require(""path""); -const fileTxt = fs.readFileSync(path.join(__dirname, ""input.txt"")); -const inputFromAdvent = fileTxt.toString(); + // Check if the guard is leaving the map + if (!guardMap.isWithinBounds(nextPosition.x, nextPosition.y)) { + break; + } -const parseInput = (input) => { - // want to take only between () and comma inside after mul. Eg mul(2,4) 2,4 - const regex = /mul\((\d+),(\d+)\)/g; - const matches = input.match(regex); - return matches.map((match) => match.slice(4, -1).split("","").map(Number)); -}; + // Check if the next position is an obstacle + if (guardMap.isObstacle(nextPosition.x, nextPosition.y)) { + guard.turnRight(); // Turn right if there's an obstacle + } else { + guard.moveForward(); // Move forward + visited.add(`${guard.x},${guard.y}`); + } + } -const parseAndMultiplyInput = (input) => { - return input - .split(""do()"") // split into chunks - .map((chunk) => chunk.split(""don't()"")[0]) // remove don't() - .map((s) => [...s.matchAll(/mul\((\d+),(\d+)\)/g)]) // find all mul pairs - .flatMap((m) => m.map((m) => m[1] * m[2])) // multiply pairs - .reduce((acc, curr) => acc + curr, 0); // sum up -}; + return visited.size; +} -const multiplyPairsTotal = (pairs) => { - return pairs.reduce((acc, pair) => acc + pair[0] * pair[1], 0); -}; +// Read the input file +const input = fs.readFileSync('input.txt', 'utf8').trim(); +const map = input.split('\n'); -const main1 = () => { - console.log(multiplyPairsTotal(parseInput(inputFromAdvent))); -}; +// Simulate the guard's movement and print the result +const distinctPositions = simulateGuardMovement(map); +console.log(`Number of distinct positions visited: ${distinctPositions}`);",node:14 +2024,6,1,"--- Day 6: Guard Gallivant --- -const main2 = () => { - console.log(parseAndMultiplyInput(inputFromAdvent)); -}; +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. -module.exports = { parseInput, multiplyPairsTotal, parseAndMultiplyInput }; +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -// main1(); -main2();",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +You start by making a map (your puzzle input) of the situation. For example: -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -For example, consider the following section of corrupted memory: +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: -Your puzzle answer was 170807108. - ---- Part Two --- - -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. - -There are two new instructions you'll need to handle: - -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. - -For example: +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); -This time, the sum of the results is 48 (2*4 + 8*5). +// Read the input file +const input = fs.readFileSync('input.txt', 'utf8'); -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require('fs'); +// Parse the grid into a 2D array +let grid = input.split('\n').map(line => line.split('')); -function question2() { - fs.readFile('./input.txt', (err, data) => { - const memory = data.toString().replace(/\r/g, '').trimEnd(); +const numRows = grid.length; +const numCols = grid[0].length; - const regex = /mul\(\d+,\d+\)|do\(\)|don't\(\)/g; +// Define directions and their corresponding movements +const directions = ['up', 'right', 'down', 'left']; +const moves = { + 'up': [-1, 0], + 'right': [0, 1], + 'down': [1, 0], + 'left': [0, -1] +}; - const matches = memory.matchAll(regex); +// Map symbols to directions +const dirSymbols = { + '^': 'up', + '>': 'right', + 'v': 'down', + '<': 'left' +}; - const instructions = []; +// Find the starting position and direction of the guard +let posRow, posCol, dir; - for (const match of matches) { - if (match[0].includes('mul')) { - instructions.push(match[0].slice(4, -1).split(',')); - } else { - instructions.push(match[0]); - } +outerLoop: +for (let i = 0; i < numRows; i++) { + for (let j = 0; j < numCols; j++) { + let cell = grid[i][j]; + if (cell in dirSymbols) { + posRow = i; + posCol = j; + dir = dirSymbols[cell]; + grid[i][j] = '.'; // Replace the starting symbol with empty space + break outerLoop; } - - let addEnabled = true; - const result = instructions.reduce((acc, instr) => { - if (typeof instr !== 'string' && addEnabled) { - return (acc += instr[0] * instr[1]); - } else if (instr === 'do()') { - addEnabled = true; - return acc; - } else if (instr === ""don't()"") { - addEnabled = false; - return acc; - } else { - return acc; - } - }, 0); - - console.log(result); - }); + } } -question2();",node:14 -2024,3,2,"--- Day 3: Mull It Over --- - -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +// Set to keep track of visited positions +let visited = new Set(); +visited.add(`${posRow},${posCol}`); -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +while (true) { + // Compute the next position + let [dRow, dCol] = moves[dir]; + let newRow = posRow + dRow; + let newCol = posCol + dCol; -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + // Check if the guard is about to leave the grid + if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) { + break; + } -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. + let cellAhead = grid[newRow][newCol]; -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + if (cellAhead === '#') { + // Turn right 90 degrees + let dirIndex = directions.indexOf(dir); + dirIndex = (dirIndex + 1) % 4; + dir = directions[dirIndex]; + } else { + // Move forward + posRow = newRow; + posCol = newCol; + visited.add(`${posRow},${posCol}`); + } +} -For example, consider the following section of corrupted memory: +// Output the number of distinct positions visited +console.log(visited.size);",node:14 +2024,6,2,"--- Day 6: Guard Gallivant --- -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -Your puzzle answer was 170807108. +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? ---- Part Two --- +You start by making a map (your puzzle input) of the situation. For example: -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -There are two new instructions you'll need to handle: +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): -For example: +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: -This time, the sum of the results is 48 (2*4 + 8*5). +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require('fs'); +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: -// Read the input file -const data = fs.readFileSync('input.txt', 'utf8'); -const inputString = data.trim(); +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -let totalSum = 0; -let mulEnabled = true; +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? -const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g; +Your puzzle answer was 4890. -let match; -while ((match = instructionRegex.exec(inputString)) !== null) { - if (match[1]) { - // Matched 'do()' - mulEnabled = true; - } else if (match[2]) { - // Matched ""don't()"" - mulEnabled = false; - } else if (match[3] && mulEnabled) { - // Matched 'mul(X,Y)' and mul is enabled - const number1 = parseInt(match[3], 10); - const number2 = parseInt(match[4], 10); - totalSum += number1 * number2; - } -} +--- Part Two --- -console.log(`Total sum of all multiplied numbers: ${totalSum}`);",node:14 -2024,3,2,"--- Day 3: Mull It Over --- +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. +Option one, put a printing press next to the guard's starting position: -For example, consider the following section of corrupted memory: - -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: -Your puzzle answer was 170807108. +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: ---- Part Two --- +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: -There are two new instructions you'll need to handle: +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); -For example: +// Directions: Up, Right, Down, Left +const DIRECTIONS = ['^', '>', 'v', '<']; -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. +// Movement offsets for each direction +const MOVEMENT = { + '^': { dx: 0, dy: -1 }, // Up + '>': { dx: 1, dy: 0 }, // Right + 'v': { dx: 0, dy: 1 }, // Down + '<': { dx: -1, dy: 0 }, // Left +}; -This time, the sum of the results is 48 (2*4 + 8*5). +// Function to find the guard's starting position and direction +const findGuard = (map) => { + for (let y = 0; y < map.length; y++) { + for (let x = 0; x < map[y].length; x++) { + if (DIRECTIONS.includes(map[y][x])) { + return { x, y, direction: map[y][x] }; + } + } + } + throw new Error('Guard not found on the map!'); +}; -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"let fs = require('fs'); -let puzzleInput = fs.readFileSync('input.txt').toString(); +// Function to turn the guard 90 degrees to the right +const turnRight = (direction) => { + const currentIndex = DIRECTIONS.indexOf(direction); + return DIRECTIONS[(currentIndex + 1) % 4]; +}; -let mul = (a, b) => a * b; +// Function to get the next position based on the current position and direction +const getNextPosition = (x, y, direction) => { + const { dx, dy } = MOVEMENT[direction]; + return { x: x + dx, y: y + dy }; +}; -let regEx = /do\(\)|don\'t\(\)|mul\([0-9]{1,3},[0-9]{1,3}\)/g; -let parts = puzzleInput.match(regEx); +// Function to check if a position is within the map boundaries +const isWithinBounds = (x, y, map) => { + return x >= 0 && x < map[0].length && y >= 0 && y < map.length; +}; -let doing = true; -let total = 0; +// Function to check if a position is an obstacle +const isObstacle = (x, y, map) => { + return map[y][x] === '#'; +}; -parts.forEach((part) => { - if (doing && part.substring(0, 3) == 'mul') { - let value = eval(part); - total += value; - } +// Function to simulate the guard's movement and check for loops +const simulateGuardMovement = (map, startX, startY, startDirection) => { + let currentDirection = startDirection; + let currentPosition = { x: startX, y: startY }; - if (part.substring(0, 3) == 'do(') doing = true; - if (part.substring(0, 3) == 'don') doing = false; -}); + const visited = new Set(); + visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`); -console.log(total);",node:14 -2024,3,2,"--- Day 3: Mull It Over --- + while (true) { + const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); -""Our computers are having issues, so I have no idea if we have any Chief Historians in stock! You're welcome to check the warehouse, though,"" says the mildly flustered shopkeeper at the North Pole Toboggan Rental Shop. The Historians head out to take a look. + // Check if the guard is leaving the map + if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { + return false; // No loop, guard leaves the map + } -The shopkeeper turns to you. ""Any chance you can see why our computers are having issues again?"" + // Check if the next position is an obstacle + if (isObstacle(nextPosition.x, nextPosition.y, map)) { + currentDirection = turnRight(currentDirection); // Turn right + } else { + currentPosition = nextPosition; // Move forward + const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`; -The computer appears to be trying to run a program, but its memory (your puzzle input) is corrupted. All of the instructions have been jumbled up! + // Check if the guard has been here before with the same direction + if (visited.has(key)) { + return true; // Loop detected + } + visited.add(key); + } + } +}; -It seems like the goal of the program is just to multiply some numbers. It does that with instructions like mul(X,Y), where X and Y are each 1-3 digit numbers. For instance, mul(44,46) multiplies 44 by 46 to get a result of 2024. Similarly, mul(123,4) would multiply 123 by 4. +// Function to count valid obstruction positions +const countValidObstructionPositions = (map) => { + const { x: startX, y: startY, direction: startDirection } = findGuard(map); + let validPositions = 0; -However, because the program's memory has been corrupted, there are also many invalid characters that should be ignored, even if they look like part of a mul instruction. Sequences like mul(4*, mul(6,9!, ?(12,34), or mul ( 2 , 4 ) do nothing. + for (let y = 0; y < map.length; y++) { + for (let x = 0; x < map[y].length; x++) { + // Skip the guard's starting position and non-empty positions + if ((x === startX && y === startY) || map[y][x] !== '.') { + continue; + } -For example, consider the following section of corrupted memory: + // Create a copy of the map with the new obstruction + const newMap = map.map((row) => row.split('')); + newMap[y][x] = '#'; + const newMapString = newMap.map((row) => row.join('')); -xmul(2,4)%&mul[3,7]!@^do_not_mul(5,5)+mul(32,64]then(mul(11,8)mul(8,5)) -Only the four highlighted sections are real mul instructions. Adding up the result of each instruction produces 161 (2*4 + 5*5 + 11*8 + 8*5). + // Simulate the guard's movement and check for loops + if (simulateGuardMovement(newMapString, startX, startY, startDirection)) { + validPositions++; + } + } + } -Scan the corrupted memory for uncorrupted mul instructions. What do you get if you add up all of the results of the multiplications? + return validPositions; +}; -Your puzzle answer was 170807108. +// Read the input file +const input = fs.readFileSync('input.txt', 'utf8').trim(); +const map = input.split('\n'); ---- Part Two --- +// Count valid obstruction positions and print the result +const validPositions = countValidObstructionPositions(map); +console.log(`Number of valid obstruction positions: ${validPositions}`);",node:14 +2024,6,2,"--- Day 6: Guard Gallivant --- -As you scan through the corrupted memory, you notice that some of the conditional statements are also still intact. If you handle some of the uncorrupted conditional statements in the program, you might be able to get an even more accurate result. +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. -There are two new instructions you'll need to handle: +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -The do() instruction enables future mul instructions. -The don't() instruction disables future mul instructions. -Only the most recent do() or don't() instruction applies. At the beginning of the program, mul instructions are enabled. +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? -For example: +You start by making a map (your puzzle input) of the situation. For example: -xmul(2,4)&mul[3,7]!^don't()_mul(5,5)+mul(32,64](mul(11,8)undo()?mul(8,5)) -This corrupted memory is similar to the example from before, but this time the mul(5,5) and mul(11,8) instructions are disabled because there is a don't() instruction before them. The other mul instructions function normally, including the one at the end that gets re-enabled by a do() instruction. +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -This time, the sum of the results is 48 (2*4 + 8*5). +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -Handle the new instructions; what do you get if you add up all of the results of just the enabled multiplications?",74838033,"const fs = require('fs'); +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): -// Function to read and process the input data -function readInput(filePath) { - try { - const data = fs.readFileSync(filePath, 'utf8'); - return data.trim(); // Return the input string after trimming any extra whitespace - } catch (error) { - console.error('Error reading the file:', error); - return ''; - } -} +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -// Function to process the instructions and compute the sum of valid multiplications -function calculateTotalSum(inputString) { - let totalSum = 0; - let mulEnabled = true; +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: - const instructionRegex = /(do\(\))|(don't\(\))|mul\((\d{1,3}),(\d{1,3})\)/g; - let match; +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): - // Iterate through each instruction in the input string - while ((match = instructionRegex.exec(inputString)) !== null) { - if (match[1]) { - mulEnabled = true; // Enable mul if 'do()' is matched - } else if (match[2]) { - mulEnabled = false; // Disable mul if ""don't()"" is matched - } else if (match[3] && mulEnabled) { - // If a valid 'mul(X,Y)' is matched and mul is enabled, multiply and add to the total sum - const number1 = parseInt(match[3], 10); - const number2 = parseInt(match[4], 10); - totalSum += number1 * number2; - } - } +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: - return totalSum; -} +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -// Main function to execute the program -function main() { - const inputString = readInput('input.txt'); - if (inputString) { - const totalSum = calculateTotalSum(inputString); - console.log(`Total sum of all multiplied numbers: ${totalSum}`); - } -} +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? -main(); // Run the main function to start the process",node:14 -2024,4,1,"--- Day 4: Ceres Search --- +Your puzzle answer was 4890. -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! +--- Part Two --- -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"import fs from ""node:fs""; +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. -const a = fs.readFileSync(""./input.txt"", ""utf8"").toString().split(""\n""); -const data = a.map((item) => item.split("""")); +Option one, put a printing press next to the guard's starting position: -const values = { - horizontalLR: 0, - horizontalRL: 0, - verticalTB: 0, - verticalBT: 0, - diagonalTLtoBR: 0, - diagonalBRtoTL: 0, - diagonalTRtoBL: 0, - diagonalBLtoTR: 0, -}; +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: -data.forEach((item, itemIdx) => { - item.forEach((child, childIdx) => { - // Horizontal (left to right) - if (child === ""X"") { - if (data[itemIdx][childIdx + 1] === ""M"") { - if (data[itemIdx][childIdx + 2] === ""A"") { - if (data[itemIdx][childIdx + 3] === ""S"") values.horizontalLR += 1; - } - } +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: - // Descending Diagonal (center to bottom right) - if (data[itemIdx + 1][childIdx + 1] === ""M"") { - if (data[itemIdx + 2][childIdx + 2] === ""A"") { - if (data[itemIdx + 3][childIdx + 3] === ""S"") - values.diagonalTLtoBR += 1; - } - } +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: - // Descending Vertical (center to bottom) - if (data[itemIdx + 1][childIdx] === ""M"") { - if (data[itemIdx + 2][childIdx] === ""A"") { - if (data[itemIdx + 3][childIdx] === ""S"") values.verticalTB += 1; - } - } +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: - // Descending diagonal (center to bottom left) - if (childIdx >= 3) { - if (data[itemIdx + 1][childIdx - 1] === ""M"") { - if (data[itemIdx + 2][childIdx - 2] === ""A"") { - if (data[itemIdx + 3][childIdx - 3] === ""S"") - values.diagonalTRtoBL += 1; - } - } - } +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: - // Horizontal (right to left) - if (childIdx >= 3) { - if (data[itemIdx][childIdx - 1] === ""M"") { - if (data[itemIdx][childIdx - 2] === ""A"") { - if (data[itemIdx][childIdx - 3] === ""S"") values.horizontalRL += 1; - } - } - } +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. - // ascending diagonal (center to top left) - if (itemIdx >= 3 && childIdx >= 3) { - if (data[itemIdx - 1][childIdx - 1] === ""M"") { - if (data[itemIdx - 2][childIdx - 2] === ""A"") { - if (data[itemIdx - 3][childIdx - 3] === ""S"") - values.diagonalBRtoTL += 1; - } - } - } +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); - // ascending vertical (center to top) - if (itemIdx >= 3) { - if (data[itemIdx - 1][childIdx] === ""M"") { - if (data[itemIdx - 2][childIdx] === ""A"") { - if (data[itemIdx - 3][childIdx] === ""S"") values.verticalBT += 1; - } - } - } +// Constants for directions and movement offsets +const DIRECTIONS = ['^', '>', 'v', '<']; +const MOVEMENT = { + '^': { dx: 0, dy: -1 }, + '>': { dx: 1, dy: 0 }, + 'v': { dx: 0, dy: 1 }, + '<': { dx: -1, dy: 0 }, +}; - // ascending diagonal (center to top right) - if (itemIdx >= 3) { - if (data[itemIdx - 1][childIdx + 1] === ""M"") { - if (data[itemIdx - 2][childIdx + 2] === ""A"") { - if (data[itemIdx - 3][childIdx + 3] === ""S"") - values.diagonalBLtoTR += 1; - } +// Class representing the Guard +class Guard { + constructor(map) { + this.map = map; + const { x, y, direction } = this.findGuard(); + this.position = { x, y }; + this.direction = direction; + } + + // Find the guard's initial position and direction + findGuard() { + for (let y = 0; y < this.map.length; y++) { + for (let x = 0; x < this.map[y].length; x++) { + if (DIRECTIONS.includes(this.map[y][x])) { + return { x, y, direction: this.map[y][x] }; } } } - }); -}); + throw new Error('Guard not found on the map!'); + } -console.log(values); -let count = 0; -Object.values(values).forEach((item) => { - count += item; -}); -console.log(count);",node:14 -2024,4,1,"--- Day 4: Ceres Search --- + // Turn the guard 90 degrees to the right + turnRight() { + const index = DIRECTIONS.indexOf(this.direction); + this.direction = DIRECTIONS[(index + 1) % 4]; + } -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! + // Get the next position based on the current position and direction + getNextPosition() { + const { dx, dy } = MOVEMENT[this.direction]; + return { x: this.position.x + dx, y: this.position.y + dy }; + } -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. + // Check if a position is within the map boundaries + isWithinBounds(x, y) { + return x >= 0 && x < this.map[0].length && y >= 0 && y < this.map.length; + } -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + // Check if a position is an obstacle + isObstacle(x, y) { + return this.map[y][x] === '#'; + } -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: + // Simulate the guard's movement + simulateMovement() { + const visited = new Set(); + visited.add(`${this.position.x},${this.position.y},${this.direction}`); -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + while (true) { + const nextPosition = this.getNextPosition(); -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"const fs = require(""fs""); -// const puzzleInput = fs.readFileSync(""./sample_input.txt"").toString().split('\n'); -const puzzleInput = fs.readFileSync(""./input.txt"").toString().split('\n'); + // Check if the guard is leaving the map + if (!this.isWithinBounds(nextPosition.x, nextPosition.y)) { + return false; // Guard exits the map + } -function findWordCount(grid, word) { - const rows = grid.length; - const cols = grid[0].length; - const wordLength = word.length; - const reverseWord = word.split('').reverse().join(''); - let count = 0; + // Check if the next position is an obstacle + if (this.isObstacle(nextPosition.x, nextPosition.y)) { + this.turnRight(); // Turn right if there's an obstacle + } else { + this.position = nextPosition; // Move forward + const key = `${this.position.x},${this.position.y},${this.direction}`; - function checkHorizontal(row, col) { - if (col <= cols - wordLength) { - const horizontalWord = grid[row].slice(col, col + wordLength); - if (horizontalWord === word || horizontalWord === reverseWord) { -count++; - // console.log(`Found ${word} horizontally at row ${row}, starting column ${col}`); - } + // Check if the guard has been here before + if (visited.has(key)) { + return true; // Loop detected } + visited.add(key); + } } + } +} - function checkVertical(row, col) { - if (row <= rows - wordLength) { - let verticalWord = ''; - for (let i = 0; i < wordLength; i++) { - verticalWord += grid[row + i][col]; - } - if (verticalWord === word || verticalWord === reverseWord) { - count++; - // console.log(`Found ${word} vertically at column ${col}, starting row ${row}`); - } - } - } +// Class to solve the problem +class Solution { + constructor(filePath) { + this.map = this.readInput(filePath); + this.guard = new Guard(this.map); + } - function checkDiagonal(row, col) { - // Diagonal down-right - if (row <= rows - wordLength && col <= cols - wordLength) { - let diagonalWord = ''; - for (let i = 0; i < wordLength; i++) { - diagonalWord += grid[row + i][col + i]; - } - if (diagonalWord === word || diagonalWord === reverseWord) { -count++; - // console.log(`Found ${word} diagonally (down-right) starting at row ${row}, column ${col}`); - } - } + // Read the input file and parse the map + readInput(filePath) { + return fs.readFileSync(filePath, 'utf8').trim().split('\n'); + } - // Diagonal down-left - if (row <= rows - wordLength && col >= wordLength - 1) { - let diagonalWord = ''; - for (let i = 0; i < wordLength; i++) { - diagonalWord += grid[row + i][col - i]; - } - if (diagonalWord === word || diagonalWord === reverseWord) { -count++; - // console.log(`Found ${word} diagonally (down-left) starting at row ${row}, column ${col}`); - } + // Count valid obstruction positions + countValidObstructionPositions() { + const { x: startX, y: startY } = this.guard.position; + let validPositions = 0; + + for (let y = 0; y < this.map.length; y++) { + for (let x = 0; x < this.map[y].length; x++) { + // Skip the guard's starting position and non-empty positions + if ((x === startX && y === startY) || this.map[y][x] !== '.') { + continue; } - } - for (let r = 0; r < rows; r++) { - for (let c = 0; c < cols; c++) { - checkHorizontal(r, c); - checkVertical(r, c); - checkDiagonal(r, c); + // Create a copy of the map with the new obstruction + const newMap = this.map.map((row) => row.split('')); + newMap[y][x] = '#'; + const newMapString = newMap.map((row) => row.join('')); + + // Simulate the guard's movement and check for loops + const guardWithNewMap = new Guard(newMapString); + if (guardWithNewMap.simulateMovement()) { + validPositions++; } + } } - return count; -} -const wordCount = findWordCount(puzzleInput, ""XMAS""); -console.log(`Part 1: ${wordCount}`);",node:14 -2024,4,1,"--- Day 4: Ceres Search --- + return validPositions; + } -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! + // Main method to solve the problem + solve() { + const validPositions = this.countValidObstructionPositions(); + console.log(`Number of valid obstruction positions: ${validPositions}`); + } +} -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. +// Instantiate the solution class and solve the problem +const solution = new Solution('input.txt'); +solution.solve();",node:14 +2024,6,2,"--- Day 6: Guard Gallivant --- -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"const fs = require('fs'); +You start by making a map (your puzzle input) of the situation. For example: -// Read the input file -const data = fs.readFileSync('input.txt', 'utf8'); -const lines = data.trim().split('\n'); -const grid = lines.map(line => line.trim().split('')); +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -const numRows = grid.length; -const numCols = grid[0].length; -const word = 'XMAS'; -let count = 0; +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -// Directions: N, NE, E, SE, S, SW, W, NW -const directions = [ - [-1, 0], // N - [-1, 1], // NE - [ 0, 1], // E - [ 1, 1], // SE - [ 1, 0], // S - [ 1, -1], // SW - [ 0, -1], // W - [-1, -1] // NW -]; +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): -for (let row = 0; row < numRows; row++) { - for (let col = 0; col < numCols; col++) { - for (let [dx, dy] of directions) { - let match = true; - for (let k = 0; k < word.length; k++) { - const x = row + k * dx; - const y = col + k * dy; - if (x < 0 || x >= numRows || y < 0 || y >= numCols || grid[x][y] !== word[k]) { - match = false; - break; - } - } - if (match) { - count++; - } - } - } -} +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -console.log(`The word ""XMAS"" appears ${count} times in the grid.`);",node:14 -2024,4,1,"--- Day 4: Ceres Search --- +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: +Your puzzle answer was 4890. -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"import fs from ""fs""; +--- Part Two --- -const countXmasOccurrences = (inputFilePath) => { - const xmasMatrix = []; +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. - try { - const text = fs.readFileSync(inputFilePath, ""utf8""); - if (!text) return 0; +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. - const rows = text.trim().split(""\n""); +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. - for (const row of rows) { - xmasMatrix.push(row.split("""")); - } +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. - let xmasCounter = 0; +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. - for (let i = 0; i < xmasMatrix.length; i++) { - for (let j = 0; j < xmasMatrix[i].length; j++) { - const currentChar = xmasMatrix[i][j]; +Option one, put a printing press next to the guard's starting position: - if (xmasMatrix?.[i - 3]?.[j - 3]) { - const topLeftDiagonal = - currentChar + - xmasMatrix[i - 1][j - 1] + - xmasMatrix[i - 2][j - 2] + - xmasMatrix[i - 3][j - 3]; +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: - if (topLeftDiagonal === ""XMAS"") xmasCounter++; - } +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: - if (xmasMatrix?.[i - 3]?.[j + 3]) { - const topRightDiagonal = - currentChar + - xmasMatrix[i - 1][j + 1] + - xmasMatrix[i - 2][j + 2] + - xmasMatrix[i - 3][j + 3]; +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: - if (topRightDiagonal === ""XMAS"") xmasCounter++; - } +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: - if (xmasMatrix?.[i + 3]?.[j - 3]) { - const botLeftDiagonal = - currentChar + - xmasMatrix[i + 1][j - 1] + - xmasMatrix[i + 2][j - 2] + - xmasMatrix[i + 3][j - 3]; +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: - if (botLeftDiagonal === ""XMAS"") xmasCounter++; - } +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. - if (xmasMatrix?.[i + 3]?.[j + 3]) { - const botRightDiagonal = - currentChar + - xmasMatrix[i + 1][j + 1] + - xmasMatrix[i + 2][j + 2] + - xmasMatrix[i + 3][j + 3]; +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); +const {log} = require('console'); - if (botRightDiagonal === ""XMAS"") xmasCounter++; +let lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); + +function findPosition() { + for (let i = 0; i < lines.length; i++) { + for (let j = 0; j < lines[0].length; j++) { + if (lines[i][j] === '^') { + return [j, i]; + } } + } +} - if (xmasMatrix[i]?.[j - 3]) { - const left = - currentChar + - xmasMatrix[i][j - 1] + - xmasMatrix[i][j - 2] + - xmasMatrix[i][j - 3]; +let [columnStart, rowStart] = findPosition(); +let [columnCurrent, rowCurrent] = [columnStart, rowStart]; +let [columnDirection, rowDirection] = [0, -1]; - if (left === ""XMAS"") xmasCounter++; - } +let visited = new Set(); - if (xmasMatrix[i]?.[j + 3]) { - const right = - currentChar + - xmasMatrix[i][j + 1] + - xmasMatrix[i][j + 2] + - xmasMatrix[i][j + 3]; +const key = (c, r) => `${c},${r}`; +visited.add(key(columnStart, rowStart)); +while (true) { + let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection]; - if (right === ""XMAS"") xmasCounter++; - } + if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) { + break; + } + if (lines[rowNext][columnNext] === '#') { + // turn right + [columnDirection, rowDirection] = [-rowDirection, columnDirection]; + } else { + visited.add(key(columnNext, rowNext)); + [columnCurrent, rowCurrent] = [columnNext, rowNext]; + } +} +log(visited.size); - if (xmasMatrix?.[i - 3]?.[j]) { - const top = - currentChar + - xmasMatrix[i - 1][j] + - xmasMatrix[i - 2][j] + - xmasMatrix[i - 3][j]; +function isEndless(columnStart, rowStart, columnDirection, rowDirection, grid) { + let [columnCurrent, rowCurrent] = [columnStart, rowStart]; + let visited = {}; + visited[key(columnStart, rowStart)] = [[columnDirection, rowDirection]]; - if (top === ""XMAS"") xmasCounter++; + while (true) { + let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection]; + + if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) { + return false; + } + if (grid[rowNext][columnNext] === '#') { + // turn right + [columnDirection, rowDirection] = [-rowDirection, columnDirection]; + } else { + let k = key(columnNext, rowNext); + let dk = key(columnDirection, rowDirection); + if (visited[k]) { + if (visited[k].includes(dk)) { + // loop confirmed + return true; + } + visited[k].push(dk); + } else { + visited[k] = [dk]; + } + [columnCurrent, rowCurrent] = [columnNext, rowNext]; } + } +} - if (xmasMatrix?.[i + 3]?.[j]) { - const bot = - currentChar + - xmasMatrix[i + 1][j] + - xmasMatrix[i + 2][j] + - xmasMatrix[i + 3][j]; +// part 2 +let blocks = new Set(); +// change every visited coordinate (except start) to # and check if it results in a loop. +for (let k of visited) { + const [c, r] = k.split(',').map(x => parseInt(x)) - if (bot === ""XMAS"") xmasCounter++; + if (!(c === columnStart && r === rowStart)) { + // clone grid with added # on next direction and check isEndless + const copy = JSON.parse(JSON.stringify(lines)); + copy[r] = copy[r].slice(0, c) + '#' + copy[r].slice(c + 1); + + if (isEndless(columnStart, rowStart, -1, 0, copy)) { + blocks.add(key(c, r)); } - } } - return xmasCounter; - } catch (err) { - console.error(err); - } -}; +} +console.log(blocks.size);",node:14 +2024,6,2,"--- Day 6: Guard Gallivant --- -const totalXmasOccurrences = countXmasOccurrences(""./puzzle-input.txt""); -console.log(totalXmasOccurrences);",node:14 -2024,4,1,"--- Day 4: Ceres Search --- +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: +You start by making a map (your puzzle input) of the situation. For example: -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear?",2434,"let fs = require('fs'); -let rows = fs.readFileSync('input.txt').toString().split(""\n""); +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): -// We need a Width and a Height - we will assume it is a rectangular wordsearch and that all rows are the same length -const WIDTH = rows[0].length; -const HEIGHT = rows.length; +....#..... +....^....# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -const DIRECTIONS = [ - [1, 0], // East - [1, 1], // South East - [0, 1], // South - [-1, 1], // South West - [-1, 0], // West - [-1, -1], // North West - [0, -1], // North - [1, -1], // North East -]; +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: -const SEARCH = 'XMAS'; +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -// Keep a running total of how many times we have found the Search Word -let runningTotal = 0; +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: -rows.forEach((row, rowIndex) => { - if (row.length > 0) { - [...row].forEach((letter, colIndex) => { - if (letter === SEARCH[0]) { - DIRECTIONS.forEach((direction) => { - for (let i = 1; i <= SEARCH.length - 1; i++) { - let coordY = rowIndex + (direction[0] * i); - let coordX = colIndex + (direction[1] * i); - if (coordY < HEIGHT && coordY >= 0 && coordX < WIDTH && coordX >= 0) { - if (rows[coordY][coordX] === SEARCH[i]) { - if (i === SEARCH.length - 1) { - runningTotal++; - break; - } - } else { - break; - } - } - } - }); - } - }); - } -}); +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -console.log(runningTotal);",node:14 -2024,4,2,"--- Day 4: Ceres Search --- +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! +Your puzzle answer was 4890. -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. +--- Part Two --- -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear? +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. -Your puzzle answer was 2434. +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. ---- Part Two --- +Option one, put a printing press next to the guard's starting position: -The Elf looks quizzically at you. Did you misunderstand the assignment? +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: -Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: -M.S -.A. -M.S -Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: -Here's the same example from before, but this time all of the X-MASes have been kept instead: +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: -.M.S...... -..A..MSMS. -.M.S.MAA.. -..A.ASMSM. -.M.S.M.... -.......... -S.S.S.S.S. -.A.A.A.A.. -M.M.M.M.M. -.......... -In this example, an X-MAS appears 9 times. +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: -Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"import fs from ""node:fs""; +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. -const a = fs.readFileSync(""./input.txt"", ""utf8"").toString().split(""\n""); -const data = a.map((item) => item.split("""")); +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); -let count = 0; +// Read the input file +const input = fs.readFileSync('input.txt', 'utf8'); -data.forEach((_, vertIdx) => { - data[vertIdx].forEach((_, horzIdx) => { - if (vertIdx >= 1 && horzIdx >= 1) { - if (data[vertIdx][horzIdx] === ""A"") { - if ( - data[vertIdx - 1][horzIdx - 1] === ""M"" && - data[vertIdx - 1][horzIdx + 1] === ""S"" && - data[vertIdx + 1][horzIdx - 1] === ""M"" && - data[vertIdx + 1][horzIdx + 1] === ""S"" - ) { - count += 1; +// Parse the grid into a 2D array +let originalGrid = input.split('\n').map(line => line.split('')); + +const numRows = originalGrid.length; +const numCols = originalGrid[0].length; + +// Define directions and their corresponding movements +const directions = ['up', 'right', 'down', 'left']; +const moves = { + 'up': [-1, 0], + 'right': [0, 1], + 'down': [1, 0], + 'left': [0, -1] +}; + +// Map symbols to directions +const dirSymbols = { + '^': 'up', + '>': 'right', + 'v': 'down', + '<': 'left' +}; + +// Find the starting position and direction of the guard +let startRow, startCol, startDir; + +outerLoop: +for (let i = 0; i < numRows; i++) { + for (let j = 0; j < numCols; j++) { + let cell = originalGrid[i][j]; + if (cell in dirSymbols) { + startRow = i; + startCol = j; + startDir = dirSymbols[cell]; + break outerLoop; } + } +} - if ( - data[vertIdx - 1][horzIdx - 1] === ""S"" && - data[vertIdx - 1][horzIdx + 1] === ""S"" && - data[vertIdx + 1][horzIdx - 1] === ""M"" && - data[vertIdx + 1][horzIdx + 1] === ""M"" - ) { - count += 1; +// Function to simulate the guard's movement +function simulate(grid) { + let posRow = startRow; + let posCol = startCol; + let dir = startDir; + + // Visited positions with direction + let visitedStates = new Set(); + visitedStates.add(`${posRow},${posCol},${dir}`); + + while (true) { + let [dRow, dCol] = moves[dir]; + let newRow = posRow + dRow; + let newCol = posCol + dCol; + + // Check if the guard is about to leave the grid + if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) { + return false; // Guard leaves the grid } - if ( - data[vertIdx - 1][horzIdx - 1] === ""M"" && - data[vertIdx - 1][horzIdx + 1] === ""M"" && - data[vertIdx + 1][horzIdx - 1] === ""S"" && - data[vertIdx + 1][horzIdx + 1] === ""S"" - ) { - count += 1; + let cellAhead = grid[newRow][newCol]; + + if (cellAhead === '#') { + // Turn right 90 degrees + let dirIndex = directions.indexOf(dir); + dirIndex = (dirIndex + 1) % 4; + dir = directions[dirIndex]; + } else { + // Move forward + posRow = newRow; + posCol = newCol; } - if ( - data[vertIdx - 1][horzIdx - 1] === ""S"" && - data[vertIdx - 1][horzIdx + 1] === ""M"" && - data[vertIdx + 1][horzIdx - 1] === ""S"" && - data[vertIdx + 1][horzIdx + 1] === ""M"" - ) { - count += 1; + let state = `${posRow},${posCol},${dir}`; + if (visitedStates.has(state)) { + return true; // Guard is in a loop } - } + visitedStates.add(state); } - }); -}); -console.log(count);",node:14 -2024,4,2,"--- Day 4: Ceres Search --- +} -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! +// Count the number of positions where adding an obstruction causes the guard to loop +let count = 0; -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. +for (let i = 0; i < numRows; i++) { + for (let j = 0; j < numCols; j++) { + // Skip if cell is not empty or is the starting position + if (originalGrid[i][j] !== '.' || (i === startRow && j === startCol)) { + continue; + } -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: + // Create a copy of the grid + let grid = originalGrid.map(row => row.slice()); -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: + // Place an obstruction at (i, j) + grid[i][j] = '#'; -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + // Simulate the guard's movement + if (simulate(grid)) { + count++; + } + } +} -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear? +// Output the total count +console.log(count);",node:14 +2024,6,2,"--- Day 6: Guard Gallivant --- -Your puzzle answer was 2434. +The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. ---- Part Two --- +You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -The Elf looks quizzically at you. Did you misunderstand the assignment? +Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? -Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: +You start by making a map (your puzzle input) of the situation. For example: -M.S -.A. -M.S -Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#..^..... +........#. +#......... +......#... +The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -Here's the same example from before, but this time all of the X-MASes have been kept instead: +Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: -.M.S...... -..A..MSMS. -.M.S.MAA.. -..A.ASMSM. -.M.S.M.... +If there is something directly in front of you, turn right 90 degrees. +Otherwise, take a step forward. +Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + +....#..... +....^....# .......... -S.S.S.S.S. -.A.A.A.A.. -M.M.M.M.M. +..#....... +.......#.. .......... -In this example, an X-MAS appears 9 times. +.#........ +........#. +#......... +......#... +Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: -Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"const fs = require(""fs""); -const filename = ""input.txt""; +....#..... +........># +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#... +Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: -var buffer, input, rows; +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#......v. +........#. +#......... +......#... +This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -try { - buffer = fs.readFileSync(__dirname + ""/"" + filename, ""utf8""); -} catch (e) { - throw e; -} +....#..... +.........# +.......... +..#....... +.......#.. +.......... +.#........ +........#. +#......... +......#v.. +By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: -input = buffer.toString(); -rows = input.split(""\n"").map(el => el.split("""")); +....#..... +....XXXXX# +....X...X. +..#.X...X. +..XXXXX#X. +..X.X.X.X. +.#XXXXXXX. +.XXXXXXX#. +#XXXXXXX.. +......#X.. +In this example, the guard will visit 41 distinct positions on your map. -function find_xmas(letter, i, j) { - let total = 0; - if (letter !== 'A') return total; // This aint it fam +Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? - // If the coords exists, check for the letter - // M ? S - // ? A ? - // M ? S - if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""M"") { - if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""S"") { - if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""M"") { - if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""S"") { - total++; - } - } - } - } +Your puzzle answer was 4890. - // M ? M - // ? A ? - // S ? S - if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""M"") { - if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""M"") { - if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""S"") { - if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""S"") { - total++; - } - } - } - } +--- Part Two --- - // S ? S - // ? A ? - // M ? M - if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""S"") { - if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""S"") { - if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""M"") { - if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""M"") { - total++; - } - } - } - } +While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. - // S ? M - // ? A ? - // S ? M - if (rows[i - 1] && rows[i - 1][j - 1] && rows[i - 1][j - 1] === ""S"") { - if (rows[i - 1] && rows[i - 1][j + 1] && rows[i - 1][j + 1] === ""M"") { - if (rows[i + 1] && rows[i + 1][j - 1] && rows[i + 1][j - 1] === ""S"") { - if (rows[i + 1] && rows[i + 1][j + 1] && rows[i + 1][j + 1] === ""M"") { - total++; - } - } - } - } +Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. +Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. - return total; -} +To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. -let found_xmass = 0; +In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. -for (let i = 0; i < rows.length; i++) { - for (let j = 0; j < rows[i].length; j++) { - found_xmass += find_xmas(rows[i][j], i, j); - } -} +Option one, put a printing press next to the guard's starting position: -console.log({ found_xmass });",node:14 -2024,4,2,"--- Day 4: Ceres Search --- +....#..... +....+---+# +....|...|. +..#.|...|. +....|..#|. +....|...|. +.#.O^---+. +........#. +#......... +......#... +Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +......O.#. +#......... +......#... +Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----+O#. +#+----+... +......#... +Option four, put an alchemical retroencabulator near the bottom left corner: -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +..|...|.#. +#O+---+... +......#... +Option five, put the alchemical retroencabulator a bit to the right instead: -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +....|.|.#. +#..O+-+... +......#... +Option six, put a tank of sovereign glue right next to the tank of universal solvent: -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: +....#..... +....+---+# +....|...|. +..#.|...|. +..+-+-+#|. +..|.|.|.|. +.#+-^-+-+. +.+----++#. +#+----++.. +......#O.. +It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear? +You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); -Your puzzle answer was 2434. +// Constants for directions and movement offsets +const DIRECTIONS = ['^', '>', 'v', '<']; +const MOVEMENT = { + '^': { dx: 0, dy: -1 }, // Up + '>': { dx: 1, dy: 0 }, // Right + 'v': { dx: 0, dy: 1 }, // Down + '<': { dx: -1, dy: 0 }, // Left +}; ---- Part Two --- +// Read the input file and parse the map +const readInput = (filePath) => { + return fs.readFileSync(filePath, 'utf8').trim().split('\n'); +}; -The Elf looks quizzically at you. Did you misunderstand the assignment? +// Find the guard's starting position and direction +const findGuard = (map) => { + for (let y = 0; y < map.length; y++) { + for (let x = 0; x < map[y].length; x++) { + if (DIRECTIONS.includes(map[y][x])) { + return { x, y, direction: map[y][x] }; + } + } + } + throw new Error('Guard not found on the map!'); +}; -Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: +// Turn the guard 90 degrees to the right +const turnRight = (direction) => { + const currentIndex = DIRECTIONS.indexOf(direction); + return DIRECTIONS[(currentIndex + 1) % 4]; +}; -M.S -.A. -M.S -Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. +// Get the next position based on the current position and direction +const getNextPosition = (x, y, direction) => { + const { dx, dy } = MOVEMENT[direction]; + return { x: x + dx, y: y + dy }; +}; -Here's the same example from before, but this time all of the X-MASes have been kept instead: +// Check if a position is within the map boundaries +const isWithinBounds = (x, y, map) => { + return x >= 0 && x < map[0].length && y >= 0 && y < map.length; +}; -.M.S...... -..A..MSMS. -.M.S.MAA.. -..A.ASMSM. -.M.S.M.... -.......... -S.S.S.S.S. -.A.A.A.A.. -M.M.M.M.M. -.......... -In this example, an X-MAS appears 9 times. +// Check if a position is an obstacle +const isObstacle = (x, y, map) => { + return map[y][x] === '#'; +}; -Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"const fs = require('fs'); +// Simulate the guard's movement and check for loops +const simulateGuardMovement = (map, startX, startY, startDirection) => { + let currentDirection = startDirection; + let currentPosition = { x: startX, y: startY }; -// Function to read the input file and split it into rows -function readInput(filePath) { - try { - const data = fs.readFileSync(filePath, 'utf-8'); - return data.split(""\n"").filter(row => row.length > 0); // Filter out any empty rows - } catch (error) { - console.error('Error reading the file:', error); - return []; - } -} + const visited = new Set(); + visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`); -// Function to check if an ""X-MAS"" pattern is found at a given position in the grid -function isXMASPattern(rows, rowIndex, colIndex, WIDTH, HEIGHT) { - // Check if we're within bounds and the letter at the center is 'A' - if (rowIndex > 0 && rowIndex < HEIGHT - 1 && colIndex > 0 && colIndex < WIDTH - 1 && rows[rowIndex][colIndex] === 'A') { - return ( - // Check for diagonals forming 'X-MAS' in both directions - ( - rows[rowIndex + 1][colIndex + 1] === 'M' && rows[rowIndex - 1][colIndex - 1] === 'S' || - rows[rowIndex + 1][colIndex + 1] === 'S' && rows[rowIndex - 1][colIndex - 1] === 'M' - ) && - ( - rows[rowIndex + 1][colIndex - 1] === 'M' && rows[rowIndex - 1][colIndex + 1] === 'S' || - rows[rowIndex + 1][colIndex - 1] === 'S' && rows[rowIndex - 1][colIndex + 1] === 'M' - ) - ); - } - return false; -} + while (true) { + const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); -// Function to count occurrences of the ""X-MAS"" pattern in the grid -function countXMASPatterns(rows, WIDTH, HEIGHT) { - let runningTotal = 0; + // Check if the guard is leaving the map + if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { + return false; // No loop, guard leaves the map + } - // Loop over each row and column to check for ""X-MAS"" patterns - rows.forEach((row, rowIndex) => { - [...row].forEach((letter, colIndex) => { - if (isXMASPattern(rows, rowIndex, colIndex, WIDTH, HEIGHT)) { - runningTotal++; + // Check if the next position is an obstacle + if (isObstacle(nextPosition.x, nextPosition.y, map)) { + currentDirection = turnRight(currentDirection); // Turn right + } else { + currentPosition = nextPosition; // Move forward + const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`; + + // Check if the guard has been here before with the same direction + if (visited.has(key)) { + return true; // Loop detected } - }); - }); + visited.add(key); + } + } +}; - return runningTotal; -} +// Count valid obstruction positions +const countValidObstructionPositions = (map) => { + const { x: startX, y: startY, direction: startDirection } = findGuard(map); + let validPositions = 0; -// Main function to orchestrate the entire process -function main() { - const rows = readInput('input.txt'); - if (rows.length === 0) return; + for (let y = 0; y < map.length; y++) { + for (let x = 0; x < map[y].length; x++) { + // Skip the guard's starting position and non-empty positions + if ((x === startX && y === startY) || map[y][x] !== '.') { + continue; + } - const WIDTH = rows[0].length; - const HEIGHT = rows.length; + // Create a copy of the map with the new obstruction + const newMap = map.map((row) => row.split('')); + newMap[y][x] = '#'; + const newMapString = newMap.map((row) => row.join('')); - // Count the occurrences of ""X-MAS"" patterns - const totalPatterns = countXMASPatterns(rows, WIDTH, HEIGHT); + // Simulate the guard's movement and check for loops + if (simulateGuardMovement(newMapString, startX, startY, startDirection)) { + validPositions++; + } + } + } - // Output the result - console.log(totalPatterns); -} + return validPositions; +}; -main(); // Run the main function",node:14 -2024,4,2,"--- Day 4: Ceres Search --- +// Main function to solve the problem +const solve = (filePath) => { + const map = readInput(filePath); + const validPositions = countValidObstructionPositions(map); + console.log(`Number of valid obstruction positions: ${validPositions}`); +}; -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! +// Run the solution +solve('input.txt');",node:14 +2024,8,1,"--- Day 8: Resonant Collinearity --- -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. +You find yourselves on the roof of a top-secret Easter Bunny installation. -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear? - -Your puzzle answer was 2434. - ---- Part Two --- - -The Elf looks quizzically at you. Did you misunderstand the assignment? - -Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: +So, for these two antennas with frequency a, they create the two antinodes marked with #: -M.S -.A. -M.S -Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: -Here's the same example from before, but this time all of the X-MASes have been kept instead: +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -.M.S...... -..A..MSMS. -.M.S.MAA.. -..A.ASMSM. -.M.S.M.... .......... -S.S.S.S.S. -.A.A.A.A.. -M.M.M.M.M. +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... .......... -In this example, an X-MAS appears 9 times. +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"let fs = require('fs'); -let rows = fs.readFileSync('input.txt').toString().split(""\n""); +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -// We need a Width and a Height - we will assume it is a rectangular wordsearch and that all rows are the same length -const WIDTH = rows[0].length; -const HEIGHT = rows.length; +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); -// Keep a running total of how many times we have found the Search Word -let runningTotal = 0; +const input = fs.readFileSync('input.txt', 'utf8').trim(); +const lines = input.split('\n'); +const height = lines.length; +const width = lines[0].length; +const antennas = {}; -rows.forEach((row, rowIndex) => { - if (row.length > 0) { - [...row].forEach((letter, colIndex) => { - if (letter === 'A') { - if ( - rowIndex > 0 && rowIndex < HEIGHT - 1 && - colIndex > 0 && colIndex < WIDTH - 1 && - ( - (rows[rowIndex + 1][colIndex + 1] === 'M' && rows[rowIndex - 1][colIndex - 1] === 'S') || - (rows[rowIndex + 1][colIndex + 1] === 'S' && rows[rowIndex - 1][colIndex - 1] === 'M') - ) && - ( - (rows[rowIndex + 1][colIndex - 1] === 'M' && rows[rowIndex - 1][colIndex + 1] === 'S') || - (rows[rowIndex + 1][colIndex - 1] === 'S' && rows[rowIndex - 1][colIndex + 1] === 'M') - ) - ) { - runningTotal++; - } - } - }); +// Collect antennas by frequency +for (let y = 0; y < height; y++) { + const line = lines[y]; + for (let x = 0; x < width; x++) { + const char = line[x]; + if (/[a-zA-Z0-9]/.test(char)) { + if (!antennas[char]) antennas[char] = []; + antennas[char].push({ x, y }); } -}); - -console.log(runningTotal);",node:14 -2024,4,2,"--- Day 4: Ceres Search --- - -""Looks like the Chief's not here. Next!"" One of The Historians pulls out a device and pushes the only button on it. After a brief flash, you recognize the interior of the Ceres monitoring station! + } +} -As the search for the Chief continues, a small Elf who lives on the station tugs on your shirt; she'd like to know if you could help her with her word search (your puzzle input). She only has to find one word: XMAS. +const antinodes = new Set(); -This word search allows words to be horizontal, vertical, diagonal, written backwards, or even overlapping other words. It's a little unusual, though, as you don't merely need to find one instance of XMAS - you need to find all of them. Here are a few ways XMAS might appear, where irrelevant characters have been replaced with .: +for (const freq in antennas) { + const positions = antennas[freq]; + const n = positions.length; + for (let i = 0; i < n; i++) { + const A = positions[i]; + for (let j = i + 1; j < n; j++) { + const B = positions[j]; + const dx = A.x - B.x; + const dy = A.y - B.y; + const D = { x: dx, y: dy }; -..X... -.SAMX. -.A..A. -XMAS.S -.X.... -The actual word search will be full of letters instead. For example: + // Antinodes occur at positions where one antenna is twice as far as the other + const tValues = [-1, 2]; -MMMSXXMASM -MSAMXMSMSA -AMXSXMAAMM -MSAMASMSMX -XMASAMXAMM -XXAMMXXAMA -SMSMSASXSS -SAXAMASAAA -MAMMMXMMMM -MXMXAXMASX -In this word search, XMAS occurs a total of 18 times; here's the same word search again, but where letters not involved in any XMAS have been replaced with .: + for (const t of tValues) { + const Px = B.x + t * D.x; + const Py = B.y + t * D.y; + if ( + Number.isInteger(Px) && + Number.isInteger(Py) && + Px >= 0 && + Px < width && + Py >= 0 && + Py < height + ) { + const key = `${Px},${Py}`; + antinodes.add(key); + } + } + } + } +} -....XXMAS. -.SAMXMS... -...S..A... -..A.A.MS.X -XMASAMX.MM -X.....XA.A -S.S.S.S.SS -.A.A.A.A.A -..M.M.M.MM -.X.X.XMASX -Take a look at the little Elf's word search. How many times does XMAS appear? +console.log(antinodes.size);",node:14 +2024,8,1,"--- Day 8: Resonant Collinearity --- -Your puzzle answer was 2434. +You find yourselves on the roof of a top-secret Easter Bunny installation. ---- Part Two --- +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! -The Elf looks quizzically at you. Did you misunderstand the assignment? +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: -Looking for the instructions, you flip over the word search to find that this isn't actually an XMAS puzzle; it's an X-MAS puzzle in which you're supposed to find two MAS in the shape of an X. One way to achieve that is like this: +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. -M.S -.A. -M.S -Irrelevant characters have again been replaced with . in the above diagram. Within the X, each MAS can be written forwards or backwards. +So, for these two antennas with frequency a, they create the two antinodes marked with #: -Here's the same example from before, but this time all of the X-MASes have been kept instead: +.......... +...#...... +.......... +....a..... +.......... +.....a.... +.......... +......#... +.......... +.......... +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: -.M.S...... -..A..MSMS. -.M.S.MAA.. -..A.ASMSM. -.M.S.M.... .......... -S.S.S.S.S. -.A.A.A.A.. -M.M.M.M.M. +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......#... .......... -In this example, an X-MAS appears 9 times. +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -Flip the word search from the instructions back over to the word search side and try again. How many times does an X-MAS appear?",1835,"const fs = require('fs'); +.......... +...#...... +#......... +....a..... +........a. +.....a.... +..#....... +......A... +.......... +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -// Read the input file and create the grid -const data = fs.readFileSync('input.txt', 'utf8'); -const lines = data.trim().split('\n'); -const grid = lines.map(line => line.trim().split('')); +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -const numRows = grid.length; -const numCols = grid[0].length; -let count = 0; +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); -// Directions for diagonals -const dir1 = [-1, -1]; // Top-left to bottom-right -const dir2 = [-1, 1]; // Top-right to bottom-left +// Read and parse the input file +const input = fs.readFileSync('input.txt', 'utf8').trim(); +const mapLines = input.split('\n'); +const mapHeight = mapLines.length; +const mapWidth = mapLines[0].length; -for (let row = 0; row < numRows; row++) { - for (let col = 0; col < numCols; col++) { - if (grid[row][col] === 'A') { - let valid1 = false; - let valid2 = false; - - // Check diagonal from top-left to bottom-right - // Check diagonal from top-left to bottom-right -if ( - row - 1 >= 0 && col - 1 >= 0 && - row + 1 < numRows && col + 1 < numCols && - ( - (grid[row - 1][col - 1] === 'M' && grid[row + 1][col + 1] === 'S') || - (grid[row - 1][col - 1] === 'S' && grid[row + 1][col + 1] === 'M') - ) - ) { - valid1 = true; - } - - // Check diagonal from top-right to bottom-left - if ( - row - 1 >= 0 && col + 1 < numCols && - row + 1 < numRows && col - 1 >= 0 && - ( - (grid[row - 1][col + 1] === 'M' && grid[row + 1][col - 1] === 'S') || - (grid[row - 1][col + 1] === 'S' && grid[row + 1][col - 1] === 'M') - ) - ) { - valid2 = true; - } - - // If both diagonals form 'MAS' or 'SAM', increment count - if (valid1 && valid2) { - count++; - } +// Function to locate antennas by frequency in the map +function extractAntennas(mapLines) { + const antennas = {}; + + mapLines.forEach((line, y) => { + Array.from(line).forEach((char, x) => { + if (/[a-zA-Z0-9]/.test(char)) { + if (!antennas[char]) { + antennas[char] = []; + } + antennas[char].push({ x, y }); + } + }); + }); + + return antennas; +} + +// Function to calculate all antinode positions +function findAntinodePositions(antennas, mapWidth, mapHeight) { + const antinodes = new Set(); + + Object.entries(antennas).forEach(([freq, positions]) => { + for (let i = 0; i < positions.length; i++) { + const firstPos = positions[i]; + for (let j = i + 1; j < positions.length; j++) { + const secondPos = positions[j]; + + // Calculate the difference between the two positions + const dx = firstPos.x - secondPos.x; + const dy = firstPos.y - secondPos.y; + + // Check for potential antinodes + [-1, 2].forEach(t => { + const Px = secondPos.x + t * dx; + const Py = secondPos.y + t * dy; + + // Check if the calculated position is within bounds + if (Px >= 0 && Px < mapWidth && Py >= 0 && Py < mapHeight && Number.isInteger(Px) && Number.isInteger(Py)) { + antinodes.add(`${Px},${Py}`); + } + }); } } - } - - console.log(`Number of X-MAS patterns found: ${count}`);",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- + }); -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. + return antinodes; +} -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +// Main execution function +function main() { + const antennas = extractAntennas(mapLines); + const antinodes = findAntinodePositions(antennas, mapWidth, mapHeight); + console.log(antinodes.size); +} -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +main();",node:14 +2024,8,1,"--- Day 8: Resonant Collinearity --- -You start by making a map (your puzzle input) of the situation. For example: +You find yourselves on the roof of a top-secret Easter Bunny installation. -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: -....#..... -....^....# .......... -..#....... -.......#.. +...#...... .......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: - -....#..... -........># +....a..... .......... -..#....... -.......#.. +.....a.... .......... -.#........ -........#. -#......... ......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: - -....#..... -.........# .......... -..#....... -.......#.. .......... -.#......v. -........#. +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... #......... +....a..... +........a. +.....a.... +..#....... ......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -....#..... -.........# .......... +...#...... +#......... +....a..... +........a. +.....a.... ..#....... -.......#.. +......A... .......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const map = input.split('\n'); +// Read input file and split into lines +const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); -// Directions: Up, Right, Down, Left -const directions = ['^', '>', 'v', '<']; -let direction = ''; -let position = { x: 0, y: 0 }; +// Parse the map into a grid of characters +const grid = input.map(line => line.split('')); -// Parse the map to find the initial position and direction of the guard -for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - if (directions.includes(map[y][x])) { - position = { x, y }; - direction = map[y][x]; - break; - } - } - if (direction) break; -} +// Function to calculate the greatest common divisor (GCD) of two numbers +const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b)); -// Directions mapping for movement -const movement = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left -}; +// Function to calculate all unique antinode positions +const calculateAntinodes = (grid) => { + const antinodes = new Set(); + const rows = grid.length; + const cols = grid[0].length; -// Set to track the visited positions -const visited = new Set(); -visited.add(`${position.x},${position.y}`); + // Iterate over all pairs of antennas + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + const frequency1 = grid[i][j]; + if (frequency1 === '.') continue; // Skip empty spaces -// Function to turn right -const turnRight = (currentDirection) => { - const idx = directions.indexOf(currentDirection); - return directions[(idx + 1) % 4]; -}; + for (let k = 0; k < rows; k++) { + for (let l = 0; l < cols; l++) { + const frequency2 = grid[k][l]; + if (frequency2 !== frequency1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies -let guardRunning = true; + // Calculate the differences in positions + const dx = k - i; + const dy = l - j; -while (guardRunning) { - // Calculate the next position - const nextX = position.x + movement[direction].dx; - const nextY = position.y + movement[direction].dy; + // Calculate the GCD to simplify the direction vector + const divisor = gcd(Math.abs(dx), Math.abs(dy)); + const stepX = dx / divisor; + const stepY = dy / divisor; - // Check if the next position is outside the map - if ( - nextX < 0 || - nextX >= map[0].length || - nextY < 0 || - nextY >= map.length - ) { - guardRunning = false; // Guard leaves the map - } else { - // Check if the next position is an obstacle - if (map[nextY][nextX] === '#') { - // Turn right - direction = turnRight(direction); - } else { - // Move forward - position.x = nextX; - position.y = nextY; - visited.add(`${position.x},${position.y}`); - } - } -} + // Calculate the two antinode positions + const antinode1X = i - stepX; + const antinode1Y = j - stepY; + const antinode2X = k + stepX; + const antinode2Y = l + stepY; -console.log(visited.size); // The number of distinct positions visited",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- + // Check if the antinodes are within the grid bounds + if (antinode1X >= 0 && antinode1X < rows && antinode1Y >= 0 && antinode1Y < cols) { + antinodes.add(`${antinode1X},${antinode1Y}`); + } + if (antinode2X >= 0 && antinode2X < rows && antinode2Y >= 0 && antinode2Y < cols) { + antinodes.add(`${antinode2X},${antinode2Y}`); + } + } + } + } + } -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. + return antinodes.size; +}; -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +// Calculate and print the number of unique antinode locations +console.log(calculateAntinodes(grid));",node:14 +2024,8,1,"--- Day 8: Resonant Collinearity --- -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +You find yourselves on the roof of a top-secret Easter Bunny installation. -You start by making a map (your puzzle input) of the situation. For example: +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +So, for these two antennas with frequency a, they create the two antinodes marked with #: -....#..... -....^....# .......... -..#....... -.......#.. +...#...... .......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: - -....#..... -........># +....a..... .......... -..#....... -.......#.. +.....a.... .......... -.#........ -........#. -#......... ......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: - -....#..... -.........# .......... -..#....... -.......#.. .......... -.#......v. -........#. +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... #......... +....a..... +........a. +.....a.... +..#....... ......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -....#..... -.........# .......... +...#...... +#......... +....a..... +........a. +.....a.... ..#....... -.......#.. +......A... .......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require(""fs""); -const inputText = ""./input.txt""; +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); -fs.readFile(inputText, ""utf8"", (err, data) => { - if (err) { - console.error('Error reading file:', err); - return; - } +// Utility function to read and split input into lines +function getInput(filePath) { + return fs.readFileSync(filePath, 'utf8').trim().split('\n'); +} - const rows = data.split(""\n"").map(row => row.split("""")); - let guardLocation = rows - .map((row, i) => { - if (row.includes(""^"")) { - // Turn guard icon into a normal traversable space - const guardLocation = row.indexOf(""^"") - rows[i][guardLocation] = "".""; - return { x: i, y: guardLocation } +// Utility function to find antennas by frequency +function findAntennas(lines) { + const antennas = {}; + + lines.forEach((line, y) => { + Array.from(line).forEach((char, x) => { + if (/[a-zA-Z0-9]/.test(char)) { + antennas[char] = antennas[char] || []; + antennas[char].push({ x, y }); } - }) - .filter(row => row)[0]; + }); + }); - console.log(part1(rows, guardLocation)); - console.log(part2(rows, guardLocation)); -}); + return antennas; +} -const directions = { - ""up"": { dx: -1, dy: 0, next: ""right"" }, - ""right"": { dx: 0, dy: 1, next: ""down"" }, - ""down"": { dx: 1, dy: 0, next: ""left"" }, - ""left"": { dx: 0, dy: -1, next: ""up"" }, -}; +// Function to calculate antinodes from antenna pairs +function calculateAntinodes(antennas, width, height) { + const antinodes = new Set(); -// Get all places guard visits -const getPlacesVisited = (rows, guardLocation) => { - let placesVisited = new Set(); - let guardDirection = ""up""; - let nextGuardLocation; - while (nextGuardLocation !== null) { - const { x, y } = guardLocation; - const { dx, dy} = directions[guardDirection]; - let possibleNextCoords = { x: x + dx, y: y + dy }; - - // Check if in bounds - if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1|| - possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) { - placesVisited.add(`${x}, ${y}`); - nextGuardLocation = null; - break; - } - - if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ""."") { - guardDirection = directions[guardDirection].next; - } else { - guardLocation = possibleNextCoords; - nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y]; - placesVisited.add(`${x}, ${y}`); - } - } - return placesVisited; -} + Object.keys(antennas).forEach((freq) => { + const positions = antennas[freq]; + const n = positions.length; -const checkInfiniteLoop = (rows, guardLocation) => { - const placesVisited = new Set(); - let guardDirection = ""up""; - let nextGuardLocation; + for (let i = 0; i < n; i++) { + const A = positions[i]; + for (let j = i + 1; j < n; j++) { + const B = positions[j]; + const dx = A.x - B.x; + const dy = A.y - B.y; - while (true) { - const { x, y } = guardLocation; - const { dx, dy} = directions[guardDirection]; - let possibleNextCoords = { x: x + dx, y: y + dy }; - - // Check if guard has been here before, and in the same direction, indicating an infinite loop - const currentPosition = `${x}, ${y}, ${guardDirection}` - if (placesVisited.has(currentPosition)) { - return true; - } - placesVisited.add(currentPosition); + // Check antinode conditions for both t = -1 and t = 2 + [-1, 2].forEach((t) => { + const Px = B.x + t * dx; + const Py = B.y + t * dy; - // Check if in bounds - if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1|| - possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) { - return false; + // Ensure that Px and Py are within bounds and valid positions + if (Number.isInteger(Px) && Number.isInteger(Py) && + Px >= 0 && Px < width && Py >= 0 && Py < height) { + const key = `${Px},${Py}`; + antinodes.add(key); + } + }); + } } + }); - if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ""."") { - guardDirection = directions[guardDirection].next; - } else { - guardLocation = possibleNextCoords; - nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y]; - } - } + return antinodes; } -const part1 = (rows, guardLocation) => getPlacesVisited(rows, guardLocation).size; - -const part2 = (rows, guardLocation) => { - // All the places the guard would normally visit (minus starting location) - const placesVisited = [...getPlacesVisited(rows, guardLocation)].slice(1); - let infiniteLoops = 0; - - for (let i = 0; i < placesVisited.length; i++) { - const [ obstacleX, obstacleY ] = placesVisited[i].split("", "").map(Number); - - // Temporarily change normal tile to obstacle - rows[obstacleX][obstacleY] = ""#""; - - if (checkInfiniteLoop(rows, guardLocation)) infiniteLoops++; +// Main function to execute the solution +function solve(filePath) { + const lines = getInput(filePath); + const height = lines.length; + const width = lines[0].length; - // Return obstacle to normal tile - rows[obstacleX][obstacleY] = "".""; - } - return infiniteLoops; -}",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- + const antennas = findAntennas(lines); + const antinodes = calculateAntinodes(antennas, width, height); -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. + console.log(antinodes.size); +} -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +// Run the solution +solve('input.txt');",node:14 +2024,8,1,"--- Day 8: Resonant Collinearity --- -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +You find yourselves on the roof of a top-secret Easter Bunny installation. -You start by making a map (your puzzle input) of the situation. For example: +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +So, for these two antennas with frequency a, they create the two antinodes marked with #: -....#..... -....^....# .......... -..#....... -.......#.. +...#...... .......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: - -....#..... -........># +....a..... .......... -..#....... -.......#.. +.....a.... .......... -.#........ -........#. -#......... ......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: - -....#..... -.........# .......... -..#....... -.......#.. .......... -.#......v. -........#. +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... #......... +....a..... +........a. +.....a.... +..#....... ......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -....#..... -.........# .......... +...#...... +#......... +....a..... +........a. +.....a.... ..#....... -.......#.. +......A... .......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: - -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -// Directions: Up, Right, Down, Left -const DIRECTIONS = ['^', '>', 'v', '<']; +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); -// Movement offsets for each direction -const MOVEMENT = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left -}; +// Read and parse the input file into a grid +const grid = fs.readFileSync('input.txt', 'utf8') + .trim() + .split('\n') + .map(line => line.split('')); -// Function to find the guard's starting position and direction -const findGuard = (map) => { - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - if (DIRECTIONS.includes(map[y][x])) { - return { x, y, direction: map[y][x] }; - } - } - } - throw new Error('Guard not found on the map!'); -}; +// Helper function to compute the greatest common divisor (GCD) +const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b); -// Function to turn the guard 90 degrees to the right -const turnRight = (direction) => { - const currentIndex = DIRECTIONS.indexOf(direction); - return DIRECTIONS[(currentIndex + 1) % 4]; -}; - -// Function to get the next position based on the current position and direction -const getNextPosition = (x, y, direction) => { - const { dx, dy } = MOVEMENT[direction]; - return { x: x + dx, y: y + dy }; -}; - -// Function to check if a position is within the map boundaries -const isWithinBounds = (x, y, map) => { - return x >= 0 && x < map[0].length && y >= 0 && y < map.length; -}; +// Function to find all unique antinode positions +const findAntinodes = (grid) => { + const rows = grid.length; + const cols = grid[0].length; + const antinodeSet = new Set(); -// Function to check if a position is an obstacle -const isObstacle = (x, y, map) => { - return map[y][x] === '#'; -}; + // Iterate through all pairs of antennas + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + const freq1 = grid[i][j]; + if (freq1 === '.') continue; // Skip empty spaces -// Function to simulate the guard's movement -const simulateGuardMovement = (map) => { - const { x, y, direction } = findGuard(map); - let currentDirection = direction; - let currentPosition = { x, y }; + for (let k = 0; k < rows; k++) { + for (let l = 0; l < cols; l++) { + const freq2 = grid[k][l]; + if (freq2 !== freq1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies - const visited = new Set(); - visited.add(`${currentPosition.x},${currentPosition.y}`); + // Calculate the direction vector between the two antennas + const deltaX = k - i; + const deltaY = l - j; + const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY)); + const stepX = deltaX / gcd; + const stepY = deltaY / gcd; - while (true) { - const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); + // Calculate the two antinode positions + const antinode1 = { x: i - stepX, y: j - stepY }; + const antinode2 = { x: k + stepX, y: l + stepY }; - // Check if the guard is leaving the map - if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { - break; + // Check if the antinodes are within the grid bounds + if (antinode1.x >= 0 && antinode1.x < rows && antinode1.y >= 0 && antinode1.y < cols) { + antinodeSet.add(`${antinode1.x},${antinode1.y}`); + } + if (antinode2.x >= 0 && antinode2.x < rows && antinode2.y >= 0 && antinode2.y < cols) { + antinodeSet.add(`${antinode2.x},${antinode2.y}`); + } + } + } + } } - // Check if the next position is an obstacle - if (isObstacle(nextPosition.x, nextPosition.y, map)) { - currentDirection = turnRight(currentDirection); // Turn right - } else { - currentPosition = nextPosition; // Move forward - visited.add(`${currentPosition.x},${currentPosition.y}`); - } - } + return antinodeSet.size; +}; - return visited.size; +// Main function to calculate and log the result +const main = () => { + const antinodeCount = findAntinodes(grid); + console.log(antinodeCount); }; -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const map = input.split('\n'); +// Execute the main function +main();",node:14 +2024,8,2,"--- Day 8: Resonant Collinearity --- -// Simulate the guard's movement and print the result -const distinctPositions = simulateGuardMovement(map); -console.log(`Number of distinct positions visited: ${distinctPositions}`);",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- +You find yourselves on the roof of a top-secret Easter Bunny installation. -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. -You start by making a map (your puzzle input) of the situation. For example: +So, for these two antennas with frequency a, they create the two antinodes marked with #: -....#..... -.........# .......... -..#....... -.......#.. +...#...... .......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. - -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: - -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): - -....#..... -....^....# +....a..... .......... -..#....... -.......#.. +.....a.... .......... -.#........ -........#. -#......... ......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: - -....#..... -........># .......... -..#....... -.......#.. .......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: -....#..... -.........# .......... -..#....... -.......#.. -.......... -.#......v. -........#. +...#...... #......... +....a..... +........a. +.....a.... +..#....... ......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -....#..... -.........# .......... +...#...... +#......... +....a..... +........a. +.....a.... ..#....... -.......#.. +......A... .......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? -// Class to represent the Guard -class Guard { - constructor(x, y, direction) { - this.x = x; - this.y = y; - this.direction = direction; - this.directions = ['^', '>', 'v', '<']; // Up, Right, Down, Left - this.movement = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left - }; - } +Your puzzle answer was 332. - // Turn the guard 90 degrees to the right - turnRight() { - const currentIndex = this.directions.indexOf(this.direction); - this.direction = this.directions[(currentIndex + 1) % 4]; - } +--- Part Two --- - // Move the guard forward in the current direction - moveForward() { - const { dx, dy } = this.movement[this.direction]; - this.x += dx; - this.y += dy; - } +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. - // Get the next position without actually moving - getNextPosition() { - const { dx, dy } = this.movement[this.direction]; - return { x: this.x + dx, y: this.y + dy }; - } -} +Whoops! -// Class to represent the Map -class Map { - constructor(grid) { - this.grid = grid; - this.width = grid[0].length; - this.height = grid.length; - } +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). - // Check if a position is within the map boundaries - isWithinBounds(x, y) { - return x >= 0 && x < this.width && y >= 0 && y < this.height; - } +So, these three T-frequency antennas now create many antinodes: - // Check if a position is an obstacle - isObstacle(x, y) { - return this.grid[y][x] === '#'; - } +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... +....#..... +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. - // Find the guard's starting position and direction - findGuard() { - for (let y = 0; y < this.height; y++) { - for (let x = 0; x < this.width; x++) { - if ('^>v<'.includes(this.grid[y][x])) { - return { x, y, direction: this.grid[y][x] }; - } - } - } - throw new Error('Guard not found on the map!'); - } -} +The original example now has 34 antinodes, including the antinodes that appear on every antenna: -// Main function to simulate the guard's movement -function simulateGuardMovement(map) { - const guardMap = new Map(map); - const { x, y, direction } = guardMap.findGuard(); - const guard = new Guard(x, y, direction); +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); - const visited = new Set(); - visited.add(`${guard.x},${guard.y}`); +const grid = fs.readFileSync('input.txt', 'utf8').trim().split('\n').map(line => line.split('')); +const rows = grid.length; +const cols = grid[0].length; - while (true) { - const nextPosition = guard.getNextPosition(); +const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b); - // Check if the guard is leaving the map - if (!guardMap.isWithinBounds(nextPosition.x, nextPosition.y)) { - break; - } +const findAntinodes = (grid) => { + const antinodeSet = new Set(); - // Check if the next position is an obstacle - if (guardMap.isObstacle(nextPosition.x, nextPosition.y)) { - guard.turnRight(); // Turn right if there's an obstacle - } else { - guard.moveForward(); // Move forward - visited.add(`${guard.x},${guard.y}`); - } - } + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + const freq1 = grid[i][j]; + if (freq1 === '.') continue; - return visited.size; -} + for (let k = 0; k < rows; k++) { + for (let l = 0; l < cols; l++) { + const freq2 = grid[k][l]; + if (freq2 !== freq1 || (i === k && j === l)) continue; -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const map = input.split('\n'); + const deltaX = k - i; + const deltaY = l - j; + const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY)); + const stepX = deltaX / gcd; + const stepY = deltaY / gcd; -// Simulate the guard's movement and print the result -const distinctPositions = simulateGuardMovement(map); -console.log(`Number of distinct positions visited: ${distinctPositions}`);",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- + let x = i + stepX; + let y = j + stepY; + while (x >= 0 && x < rows && y >= 0 && y < cols) { + antinodeSet.add(`${x},${y}`); + x += stepX; + y += stepY; + } -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. + x = i - stepX; + y = j - stepY; + while (x >= 0 && x < rows && y >= 0 && y < cols) { + antinodeSet.add(`${x},${y}`); + x -= stepX; + y -= stepY; + } + } + } + } + } -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + return antinodeSet.size; +}; -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +console.log(findAntinodes(grid));",node:14 +2024,8,2,"--- Day 8: Resonant Collinearity --- -You start by making a map (your puzzle input) of the situation. For example: +You find yourselves on the roof of a top-secret Easter Bunny installation. -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + +So, for these two antennas with frequency a, they create the two antinodes marked with #: -....#..... -....^....# .......... -..#....... -.......#.. +...#...... .......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: - -....#..... -........># +....a..... .......... -..#....... -.......#.. +.....a.... .......... -.#........ -........#. -#......... ......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: - -....#..... -.........# .......... -..#....... -.......#.. .......... -.#......v. -........#. +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... #......... +....a..... +........a. +.....a.... +..#....... ......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -....#..... -.........# .......... +...#...... +#......... +....a..... +........a. +.....a.... ..#....... -.......#.. +......A... .......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8'); +Your puzzle answer was 332. -// Parse the grid into a 2D array -let grid = input.split('\n').map(line => line.split('')); +--- Part Two --- -const numRows = grid.length; -const numCols = grid[0].length; +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. -// Define directions and their corresponding movements -const directions = ['up', 'right', 'down', 'left']; -const moves = { - 'up': [-1, 0], - 'right': [0, 1], - 'down': [1, 0], - 'left': [0, -1] -}; +Whoops! -// Map symbols to directions -const dirSymbols = { - '^': 'up', - '>': 'right', - 'v': 'down', - '<': 'left' -}; +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). -// Find the starting position and direction of the guard -let posRow, posCol, dir; +So, these three T-frequency antennas now create many antinodes: -outerLoop: -for (let i = 0; i < numRows; i++) { - for (let j = 0; j < numCols; j++) { - let cell = grid[i][j]; - if (cell in dirSymbols) { - posRow = i; - posCol = j; - dir = dirSymbols[cell]; - grid[i][j] = '.'; // Replace the starting symbol with empty space - break outerLoop; - } - } -} +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... +....#..... +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. -// Set to keep track of visited positions -let visited = new Set(); -visited.add(`${posRow},${posCol}`); +The original example now has 34 antinodes, including the antinodes that appear on every antenna: -while (true) { - // Compute the next position - let [dRow, dCol] = moves[dir]; - let newRow = posRow + dRow; - let newCol = posCol + dCol; +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); - // Check if the guard is about to leave the grid - if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) { - break; - } +// Load the grid from the input file +const loadGrid = (filePath) => { + return fs.readFileSync(filePath, 'utf8') + .trim() + .split('\n') + .map(row => row.split('')); +}; - let cellAhead = grid[newRow][newCol]; +// Calculate the greatest common divisor (GCD) of two numbers +const gcd = (a, b) => { + while (b !== 0) [a, b] = [b, a % b]; + return a; +}; - if (cellAhead === '#') { - // Turn right 90 degrees - let dirIndex = directions.indexOf(dir); - dirIndex = (dirIndex + 1) % 4; - dir = directions[dirIndex]; - } else { - // Move forward - posRow = newRow; - posCol = newCol; - visited.add(`${posRow},${posCol}`); +// Find all unique antinode positions in the grid +const findAntinodes = (grid) => { + const rows = grid.length; + const cols = grid[0].length; + const antinodes = new Set(); + + // Iterate through all pairs of antennas + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + const freq = grid[i][j]; + if (freq === '.') continue; // Skip empty spaces + + for (let k = 0; k < rows; k++) { + for (let l = 0; l < cols; l++) { + if (grid[k][l] !== freq || (i === k && j === l)) continue; // Skip same antenna or different frequencies + + // Calculate the direction vector + const dx = k - i; + const dy = l - j; + const divisor = gcd(Math.abs(dx), Math.abs(dy)); + const stepX = dx / divisor; + const stepY = dy / divisor; + + // Traverse in the direction of the vector + let x = i + stepX; + let y = j + stepY; + while (x >= 0 && x < rows && y >= 0 && y < cols) { + antinodes.add(`${x},${y}`); + x += stepX; + y += stepY; + } + + // Traverse in the opposite direction + x = i - stepX; + y = j - stepY; + while (x >= 0 && x < rows && y >= 0 && y < cols) { + antinodes.add(`${x},${y}`); + x -= stepX; + y -= stepY; + } + } + } + } } -} -// Output the number of distinct positions visited -console.log(visited.size);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- + return antinodes.size; +}; -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +// Main function to execute the solution +const main = () => { + const grid = loadGrid('input.txt'); + const result = findAntinodes(grid); + console.log(result); +}; -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +// Run the program +main();",node:14 +2024,8,2,"--- Day 8: Resonant Collinearity --- -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +You find yourselves on the roof of a top-secret Easter Bunny installation. -You start by making a map (your puzzle input) of the situation. For example: +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +So, for these two antennas with frequency a, they create the two antinodes marked with #: -....#..... -....^....# .......... -..#....... -.......#.. +...#...... .......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: - -....#..... -........># +....a..... .......... -..#....... -.......#.. +.....a.... .......... -.#........ -........#. -#......... ......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: - -....#..... -.........# .......... -..#....... -.......#.. .......... -.#......v. -........#. +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + +.......... +...#...... #......... +....a..... +........a. +.....a.... +..#....... ......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -....#..... -.........# .......... +...#...... +#......... +....a..... +........a. +.....a.... ..#....... -.......#.. +......A... .......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? -Your puzzle answer was 4890. +Your puzzle answer was 332. --- Part Two --- -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. +Whoops! -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. - -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. - -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). -Option one, put a printing press next to the guard's starting position: +So, these three T-frequency antennas now create many antinodes: +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... ....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: +The original example now has 34 antinodes, including the antinodes that appear on every antenna: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: +// Helper function to compute the greatest common divisor (GCD) of two numbers +const computeGCD = (a, b) => { + while (b !== 0) { + [a, b] = [b, a % b]; + } + return Math.abs(a); +}; -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: +// Function to extract antennas from the input grid and organize them by frequency +const parseAntennas = (grid) => { + const antennas = {}; + + grid.forEach((line, y) => { + [...line].forEach((char, x) => { + if (/[a-zA-Z0-9]/.test(char)) { + if (!antennas[char]) { + antennas[char] = []; + } + antennas[char].push({ x, y }); + } + }); + }); -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. + return antennas; +}; -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); +// Function to gather all unique antinode positions in the grid +const calculateAntinodes = (antennas, width, height) => { + const antinodes = new Set(); + + Object.entries(antennas).forEach(([freq, positions]) => { + const numPositions = positions.length; + + for (let i = 0; i < numPositions; i++) { + const first = positions[i]; -// Directions: Up, Right, Down, Left -const DIRECTIONS = ['^', '>', 'v', '<']; + for (let j = i + 1; j < numPositions; j++) { + const second = positions[j]; + let dx = second.x - first.x; + let dy = second.y - first.y; -// Movement offsets for each direction -const MOVEMENT = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left -}; + // Reduce the differences by the greatest common divisor (gcd) + const gcdValue = computeGCD(dx, dy); + dx /= gcdValue; + dy /= gcdValue; -// Function to find the guard's starting position and direction -const findGuard = (map) => { - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - if (DIRECTIONS.includes(map[y][x])) { - return { x, y, direction: map[y][x] }; + // Add antinodes along the line in both directions + addAntinodesAlongLine(first.x, first.y, dx, dy, width, height, antinodes); + addAntinodesAlongLine(first.x - dx, first.y - dy, -dx, -dy, width, height, antinodes); } } - } - throw new Error('Guard not found on the map!'); -}; + }); -// Function to turn the guard 90 degrees to the right -const turnRight = (direction) => { - const currentIndex = DIRECTIONS.indexOf(direction); - return DIRECTIONS[(currentIndex + 1) % 4]; + return antinodes; }; -// Function to get the next position based on the current position and direction -const getNextPosition = (x, y, direction) => { - const { dx, dy } = MOVEMENT[direction]; - return { x: x + dx, y: y + dy }; -}; +// Function to add antinode positions along a specific line direction +const addAntinodesAlongLine = (startX, startY, dx, dy, width, height, antinodes) => { + let x = startX; + let y = startY; -// Function to check if a position is within the map boundaries -const isWithinBounds = (x, y, map) => { - return x >= 0 && x < map[0].length && y >= 0 && y < map.length; + // Add positions while moving along the line + while (x >= 0 && x < width && y >= 0 && y < height) { + const key = `${x},${y}`; + antinodes.add(key); + x += dx; + y += dy; + } }; -// Function to check if a position is an obstacle -const isObstacle = (x, y, map) => { - return map[y][x] === '#'; +// Main execution function +const main = () => { + const input = fs.readFileSync('input.txt', 'utf8').trim(); + const grid = input.split('\n'); + const height = grid.length; + const width = grid[0].length; + + // Parse the antennas from the grid + const antennas = parseAntennas(grid); + + // Calculate all unique antinode positions + const antinodes = calculateAntinodes(antennas, width, height); + + // Output the number of unique antinodes + console.log(antinodes.size); }; -// Function to simulate the guard's movement and check for loops -const simulateGuardMovement = (map, startX, startY, startDirection) => { - let currentDirection = startDirection; - let currentPosition = { x: startX, y: startY }; - - const visited = new Set(); - visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`); +// Run the program +main();",node:14 +2024,8,2,"--- Day 8: Resonant Collinearity --- - while (true) { - const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); +You find yourselves on the roof of a top-secret Easter Bunny installation. - // Check if the guard is leaving the map - if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { - return false; // No loop, guard leaves the map - } +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! - // Check if the next position is an obstacle - if (isObstacle(nextPosition.x, nextPosition.y, map)) { - currentDirection = turnRight(currentDirection); // Turn right - } else { - currentPosition = nextPosition; // Move forward - const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`; +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: - // Check if the guard has been here before with the same direction - if (visited.has(key)) { - return true; // Loop detected - } - visited.add(key); - } - } -}; +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. -// Function to count valid obstruction positions -const countValidObstructionPositions = (map) => { - const { x: startX, y: startY, direction: startDirection } = findGuard(map); - let validPositions = 0; +So, for these two antennas with frequency a, they create the two antinodes marked with #: - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - // Skip the guard's starting position and non-empty positions - if ((x === startX && y === startY) || map[y][x] !== '.') { - continue; - } - - // Create a copy of the map with the new obstruction - const newMap = map.map((row) => row.split('')); - newMap[y][x] = '#'; - const newMapString = newMap.map((row) => row.join('')); - - // Simulate the guard's movement and check for loops - if (simulateGuardMovement(newMapString, startX, startY, startDirection)) { - validPositions++; - } - } - } - - return validPositions; -}; - -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const map = input.split('\n'); - -// Count valid obstruction positions and print the result -const validPositions = countValidObstructionPositions(map); -console.log(`Number of valid obstruction positions: ${validPositions}`);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- - -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. - -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. - -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? - -You start by making a map (your puzzle input) of the situation. For example: - -....#..... -.........# .......... -..#....... -.......#.. +...#...... .......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. - -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: - -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): - -....#..... -....^....# +....a..... .......... -..#....... -.......#.. +.....a.... .......... -.#........ -........#. -#......... ......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: - -....#..... -........># .......... -..#....... -.......#.. .......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: -....#..... -.........# -.......... -..#....... -.......#.. .......... -.#......v. -........#. +...#...... #......... +....a..... +........a. +.....a.... +..#....... ......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -....#..... -.........# .......... +...#...... +#......... +....a..... +........a. +.....a.... ..#....... -.......#.. +......A... .......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? -Your puzzle answer was 4890. +Your puzzle answer was 332. --- Part Two --- -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. - -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. - -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. - -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. +Whoops! -Option one, put a printing press next to the guard's starting position: +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). -....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: +So, these three T-frequency antennas now create many antinodes: +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... ....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: +The original example now has 34 antinodes, including the antinodes that appear on every antenna: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: +// Load and parse the input file into a grid +const loadGrid = () => { + return fs.readFileSync('input.txt', 'utf8') + .trim() + .split('\n') + .map(line => line.split('')); +}; -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. +// Compute the greatest common divisor (GCD) of two numbers +const calculateGCD = (a, b) => { + while (b !== 0) { + [a, b] = [b, a % b]; + } + return a; +}; -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); +// Find all unique antinode positions in the grid +const calculateAntinodes = (grid) => { + const rows = grid.length; + const cols = grid[0].length; + const antinodes = new Set(); -// Constants for directions and movement offsets -const DIRECTIONS = ['^', '>', 'v', '<']; -const MOVEMENT = { - '^': { dx: 0, dy: -1 }, - '>': { dx: 1, dy: 0 }, - 'v': { dx: 0, dy: 1 }, - '<': { dx: -1, dy: 0 }, -}; - -// Class representing the Guard -class Guard { - constructor(map) { - this.map = map; - const { x, y, direction } = this.findGuard(); - this.position = { x, y }; - this.direction = direction; - } - - // Find the guard's initial position and direction - findGuard() { - for (let y = 0; y < this.map.length; y++) { - for (let x = 0; x < this.map[y].length; x++) { - if (DIRECTIONS.includes(this.map[y][x])) { - return { x, y, direction: this.map[y][x] }; - } - } - } - throw new Error('Guard not found on the map!'); - } - - // Turn the guard 90 degrees to the right - turnRight() { - const index = DIRECTIONS.indexOf(this.direction); - this.direction = DIRECTIONS[(index + 1) % 4]; - } - - // Get the next position based on the current position and direction - getNextPosition() { - const { dx, dy } = MOVEMENT[this.direction]; - return { x: this.position.x + dx, y: this.position.y + dy }; - } - - // Check if a position is within the map boundaries - isWithinBounds(x, y) { - return x >= 0 && x < this.map[0].length && y >= 0 && y < this.map.length; - } - - // Check if a position is an obstacle - isObstacle(x, y) { - return this.map[y][x] === '#'; - } - - // Simulate the guard's movement - simulateMovement() { - const visited = new Set(); - visited.add(`${this.position.x},${this.position.y},${this.direction}`); + // Iterate through all pairs of antennas + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + const frequency = grid[i][j]; + if (frequency === '.') continue; // Skip empty spaces - while (true) { - const nextPosition = this.getNextPosition(); + for (let k = 0; k < rows; k++) { + for (let l = 0; l < cols; l++) { + if (grid[k][l] !== frequency || (i === k && j === l)) continue; // Skip same antenna or different frequencies - // Check if the guard is leaving the map - if (!this.isWithinBounds(nextPosition.x, nextPosition.y)) { - return false; // Guard exits the map - } + // Calculate the direction vector between the two antennas + const dx = k - i; + const dy = l - j; + const gcd = calculateGCD(Math.abs(dx), Math.abs(dy)); + const stepX = dx / gcd; + const stepY = dy / gcd; - // Check if the next position is an obstacle - if (this.isObstacle(nextPosition.x, nextPosition.y)) { - this.turnRight(); // Turn right if there's an obstacle - } else { - this.position = nextPosition; // Move forward - const key = `${this.position.x},${this.position.y},${this.direction}`; + // Traverse in the direction of the vector to find antinodes + let x = i + stepX; + let y = j + stepY; + while (x >= 0 && x < rows && y >= 0 && y < cols) { + antinodes.add(`${x},${y}`); + x += stepX; + y += stepY; + } - // Check if the guard has been here before - if (visited.has(key)) { - return true; // Loop detected + // Traverse in the opposite direction to find antinodes + x = i - stepX; + y = j - stepY; + while (x >= 0 && x < rows && y >= 0 && y < cols) { + antinodes.add(`${x},${y}`); + x -= stepX; + y -= stepY; + } + } + } } - visited.add(key); - } } - } -} - -// Class to solve the problem -class Solution { - constructor(filePath) { - this.map = this.readInput(filePath); - this.guard = new Guard(this.map); - } - - // Read the input file and parse the map - readInput(filePath) { - return fs.readFileSync(filePath, 'utf8').trim().split('\n'); - } - - // Count valid obstruction positions - countValidObstructionPositions() { - const { x: startX, y: startY } = this.guard.position; - let validPositions = 0; - - for (let y = 0; y < this.map.length; y++) { - for (let x = 0; x < this.map[y].length; x++) { - // Skip the guard's starting position and non-empty positions - if ((x === startX && y === startY) || this.map[y][x] !== '.') { - continue; - } - - // Create a copy of the map with the new obstruction - const newMap = this.map.map((row) => row.split('')); - newMap[y][x] = '#'; - const newMapString = newMap.map((row) => row.join('')); - // Simulate the guard's movement and check for loops - const guardWithNewMap = new Guard(newMapString); - if (guardWithNewMap.simulateMovement()) { - validPositions++; - } - } - } + return antinodes.size; +}; - return validPositions; - } +// Main function to execute the solution +const main = () => { + const grid = loadGrid(); + const antinodeCount = calculateAntinodes(grid); + console.log(antinodeCount); +}; - // Main method to solve the problem - solve() { - const validPositions = this.countValidObstructionPositions(); - console.log(`Number of valid obstruction positions: ${validPositions}`); - } -} +// Run the main function +main();",node:14 +2024,8,2,"--- Day 8: Resonant Collinearity --- -// Instantiate the solution class and solve the problem -const solution = new Solution('input.txt'); -solution.solve();",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +You find yourselves on the roof of a top-secret Easter Bunny installation. -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +............ +........0... +.....0...... +.......0.... +....0....... +......A..... +............ +............ +........A... +.........A.. +............ +............ +The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. -You start by making a map (your puzzle input) of the situation. For example: +So, for these two antennas with frequency a, they create the two antinodes marked with #: -....#..... -.........# .......... -..#....... -.......#.. +...#...... .......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. - -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: - -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): - -....#..... -....^....# +....a..... .......... -..#....... -.......#.. +.....a.... .......... -.#........ -........#. -#......... ......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: - -....#..... -........># .......... -..#....... -.......#.. .......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: -....#..... -.........# -.......... -..#....... -.......#.. .......... -.#......v. -........#. +...#...... #......... +....a..... +........a. +.....a.... +..#....... ......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +.......... +.......... +Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: -....#..... -.........# .......... +...#...... +#......... +....a..... +........a. +.....a.... ..#....... -.......#.. +......A... .......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +.......... +The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +......#....# +...#....0... +....#0....#. +..#....0.... +....0....#.. +.#....A..... +...#........ +#......#.... +........A... +.........A.. +..........#. +..........#. +Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? +Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? -Your puzzle answer was 4890. +Your puzzle answer was 332. --- Part Two --- -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. +Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. +Whoops! -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. +After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. +So, these three T-frequency antennas now create many antinodes: -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. +T....#.... +...T...... +.T....#... +.........# +..#....... +.......... +...#...... +.......... +....#..... +.......... +In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. -Option one, put a printing press next to the guard's starting position: +The original example now has 34 antinodes, including the antinodes that appear on every antenna: -....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: +##....#....# +.#.#....0... +..#.#0....#. +..##...0.... +....0....#.. +.#...#A....# +...#..#..... +#....#.#.... +..#.....A... +....#....A.. +.#........#. +...#......## +Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: +const input = fs.readFileSync('input.txt', 'utf8').trim(); +const lines = input.split('\n'); +const height = lines.length; +const width = lines[0].length; +const antennas = {}; -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: +// Collect antennas by frequency +for (let y = 0; y < height; y++) { + const line = lines[y]; + for (let x = 0; x < width; x++) { + const char = line[x]; + if (/[a-zA-Z0-9]/.test(char)) { + if (!antennas[char]) antennas[char] = []; + antennas[char].push({ x, y }); + } + } +} -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: +const antinodes = new Set(); -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: +function gcd(a, b) { + while (b !== 0) { + [a, b] = [b, a % b]; + } + return Math.abs(a); +} -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. +for (const freq in antennas) { + const positions = antennas[freq]; + const n = positions.length; + for (let i = 0; i < n; i++) { + const A = positions[i]; + for (let j = i + 1; j < n; j++) { + const B = positions[j]; + let dx = B.x - A.x; + let dy = B.y - A.y; + const stepGCD = gcd(dx, dy); + dx /= stepGCD; + dy /= stepGCD; -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); -const {log} = require('console'); + // Include positions along the line in both directions + const points = []; -let lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); + // From A towards B + let x = A.x; + let y = A.y; + while (x >= 0 && x < width && y >= 0 && y < height) { + const key = `${x},${y}`; + antinodes.add(key); + x += dx; + y += dy; + } -function findPosition() { - for (let i = 0; i < lines.length; i++) { - for (let j = 0; j < lines[0].length; j++) { - if (lines[i][j] === '^') { - return [j, i]; - } - } + // From A in the opposite direction + x = A.x - dx; + y = A.y - dy; + while (x >= 0 && x < width && y >= 0 && y < height) { + const key = `${x},${y}`; + antinodes.add(key); + x -= dx; + y -= dy; + } } + } } -let [columnStart, rowStart] = findPosition(); -let [columnCurrent, rowCurrent] = [columnStart, rowStart]; -let [columnDirection, rowDirection] = [0, -1]; +console.log(antinodes.size);",node:14 +2024,9,1,"--- Day 9: Disk Fragmenter --- -let visited = new Set(); +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. -const key = (c, r) => `${c},${r}`; -visited.add(key(columnStart, rowStart)); -while (true) { - let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection]; +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. - if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) { - break; - } - if (lines[rowNext][columnNext] === '#') { - // turn right - [columnDirection, rowDirection] = [-rowDirection, columnDirection]; - } else { - visited.add(key(columnNext, rowNext)); - [columnCurrent, rowCurrent] = [columnNext, rowNext]; - } -} -log(visited.size); +He shows you the disk map (your puzzle input) he's already generated. For example: -function isEndless(columnStart, rowStart, columnDirection, rowDirection, grid) { - let [columnCurrent, rowCurrent] = [columnStart, rowStart]; - let visited = {}; - visited[key(columnStart, rowStart)] = [[columnDirection, rowDirection]]; +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. - while (true) { - let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection]; +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). - if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) { - return false; - } - if (grid[rowNext][columnNext] === '#') { - // turn right - [columnDirection, rowDirection] = [-rowDirection, columnDirection]; - } else { - let k = key(columnNext, rowNext); - let dk = key(columnDirection, rowDirection); - if (visited[k]) { - if (visited[k].includes(dk)) { - // loop confirmed - return true; - } - visited[k].push(dk); - } else { - visited[k] = [dk]; - } - [columnCurrent, rowCurrent] = [columnNext, rowNext]; - } - } -} +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: -// part 2 -let blocks = new Set(); -// change every visited coordinate (except start) to # and check if it results in a loop. -for (let k of visited) { - const [c, r] = k.split(',').map(x => parseInt(x)) - - if (!(c === columnStart && r === rowStart)) { - // clone grid with added # on next direction and check isEndless - const copy = JSON.parse(JSON.stringify(lines)); - copy[r] = copy[r].slice(0, c) + '#' + copy[r].slice(c + 1); +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: - if (isEndless(columnStart, rowStart, -1, 0, copy)) { - blocks.add(key(c, r)); - } - } -} -console.log(blocks.size);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. -You start by making a map (your puzzle input) of the situation. For example: +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"const fs = require('fs'); -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +// Load the disk map from the input file +const loadDiskMap = (filePath) => { + return fs.readFileSync(filePath, 'utf8').trim(); +}; -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +// Parse the disk map into a list of blocks +const parseDiskMap = (diskMap) => { + const blocks = []; + let isFile = true; + let fileId = 0; -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + for (const char of diskMap) { + const length = parseInt(char, 10); + if (isFile) { + // Add file blocks with the current file ID + for (let i = 0; i < length; i++) { + blocks.push(fileId); + } + fileId++; + } else { + // Add free space blocks represented by -1 + for (let i = 0; i < length; i++) { + blocks.push(-1); + } + } + // Alternate between file and free space + isFile = !isFile; + } -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + return blocks; +}; -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +// Compact the disk by moving file blocks to the leftmost free space +const compactDisk = (blocks) => { + while (true) { + const leftmostFreeIndex = blocks.indexOf(-1); + if (leftmostFreeIndex === -1) break; // No free space left -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + let lastFileIndex = blocks.length - 1; + while (lastFileIndex > leftmostFreeIndex && blocks[lastFileIndex] === -1) { + lastFileIndex--; + } -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + if (lastFileIndex <= leftmostFreeIndex) break; // No file blocks to move -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. + // Move the last file block to the leftmost free space + blocks[leftmostFreeIndex] = blocks[lastFileIndex]; + blocks[lastFileIndex] = -1; + } -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + return blocks; +}; -Your puzzle answer was 4890. +// Calculate the filesystem checksum +const calculateChecksum = (blocks) => { + return blocks.reduce((sum, block, index) => { + return block !== -1 ? sum + index * block : sum; + }, 0); +}; ---- Part Two --- +// Main function to execute the solution +const main = () => { + const diskMap = loadDiskMap('input.txt'); + const blocks = parseDiskMap(diskMap); + const compactedBlocks = compactDisk(blocks); + const checksum = calculateChecksum(compactedBlocks); + console.log(checksum); +}; -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. +// Run the program +main();",node:14 +2024,9,1,"--- Day 9: Disk Fragmenter --- -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. +He shows you the disk map (your puzzle input) he's already generated. For example: -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. -Option one, put a printing press next to the guard's starting position: +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). -....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: - -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. - -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8'); +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. -// Parse the grid into a 2D array -let originalGrid = input.split('\n').map(line => line.split('')); +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"const fs = require('fs'); -const numRows = originalGrid.length; -const numCols = originalGrid[0].length; +// Helper function to parse the input disk map into an array of file lengths and free space lengths +const parseDiskMap = (input) => { + const diskLengths = input.split('').map(Number); + let disk = []; + let fileId = 0; + let isFile = true; -// Define directions and their corresponding movements -const directions = ['up', 'right', 'down', 'left']; -const moves = { - 'up': [-1, 0], - 'right': [0, 1], - 'down': [1, 0], - 'left': [0, -1] -}; + // Build the initial disk representation by alternating between file blocks and free space blocks + diskLengths.forEach((length) => { + if (isFile) { + // Add file blocks + disk.push(...Array(length).fill(fileId)); + fileId++; + } else { + // Add free space blocks represented by -1 + disk.push(...Array(length).fill(-1)); + } + isFile = !isFile; // Toggle between file and free space + }); -// Map symbols to directions -const dirSymbols = { - '^': 'up', - '>': 'right', - 'v': 'down', - '<': 'left' + return disk; }; -// Find the starting position and direction of the guard -let startRow, startCol, startDir; +// Helper function to simulate the compaction of files on the disk +const compactDisk = (disk) => { + let moved = true; -outerLoop: -for (let i = 0; i < numRows; i++) { - for (let j = 0; j < numCols; j++) { - let cell = originalGrid[i][j]; - if (cell in dirSymbols) { - startRow = i; - startCol = j; - startDir = dirSymbols[cell]; - break outerLoop; + while (moved) { + moved = false; + + // Find the leftmost free space index + let leftmostFreeIndex = disk.indexOf(-1); + if (leftmostFreeIndex === -1) { + // No free space left, disk is compacted + break; } - } -} - -// Function to simulate the guard's movement -function simulate(grid) { - let posRow = startRow; - let posCol = startCol; - let dir = startDir; - - // Visited positions with direction - let visitedStates = new Set(); - visitedStates.add(`${posRow},${posCol},${dir}`); - while (true) { - let [dRow, dCol] = moves[dir]; - let newRow = posRow + dRow; - let newCol = posCol + dCol; - - // Check if the guard is about to leave the grid - if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) { - return false; // Guard leaves the grid + // Find the last file block index + let lastFileIndex = disk.length - 1; + while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) { + lastFileIndex--; } - let cellAhead = grid[newRow][newCol]; - - if (cellAhead === '#') { - // Turn right 90 degrees - let dirIndex = directions.indexOf(dir); - dirIndex = (dirIndex + 1) % 4; - dir = directions[dirIndex]; - } else { - // Move forward - posRow = newRow; - posCol = newCol; + if (lastFileIndex <= leftmostFreeIndex) { + // No file blocks to move + break; } - let state = `${posRow},${posCol},${dir}`; - if (visitedStates.has(state)) { - return true; // Guard is in a loop - } - visitedStates.add(state); + // Move the last file block to the leftmost free space + disk[leftmostFreeIndex] = disk[lastFileIndex]; + disk[lastFileIndex] = -1; + + // Set moved flag to true to keep going + moved = true; } -} -// Count the number of positions where adding an obstruction causes the guard to loop -let count = 0; + return disk; +}; -for (let i = 0; i < numRows; i++) { - for (let j = 0; j < numCols; j++) { - // Skip if cell is not empty or is the starting position - if (originalGrid[i][j] !== '.' || (i === startRow && j === startCol)) { - continue; +// Helper function to calculate the checksum of the compacted disk +const calculateChecksum = (disk) => { + return disk.reduce((checksum, block, index) => { + if (block !== -1) { + checksum += index * block; // Sum the product of position and file ID } + return checksum; + }, 0); +}; - // Create a copy of the grid - let grid = originalGrid.map(row => row.slice()); +// Main function to orchestrate the solution +const calculateDiskChecksum = (filePath) => { + const input = fs.readFileSync(filePath, 'utf-8').trim(); - // Place an obstruction at (i, j) - grid[i][j] = '#'; + // Step 1: Parse the disk map into the initial disk representation + let disk = parseDiskMap(input); - // Simulate the guard's movement - if (simulate(grid)) { - count++; - } - } -} + // Step 2: Compact the disk by moving file blocks to the leftmost free space + disk = compactDisk(disk); -// Output the total count -console.log(count);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- + // Step 3: Calculate and return the checksum + return calculateChecksum(disk); +}; -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +// Output the resulting checksum +const checksum = calculateDiskChecksum('input.txt'); +console.log(checksum);",node:14 +2024,9,1,"--- Day 9: Disk Fragmenter --- -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. -You start by making a map (your puzzle input) of the situation. For example: +He shows you the disk map (your puzzle input) he's already generated. For example: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: - -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. - -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? - -Your puzzle answer was 4890. - ---- Part Two --- +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"const fs = require('fs'); -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. +// Read and parse the input from the file +const getInput = (filePath) => { + const input = fs.readFileSync(filePath, 'utf-8').trim(); + return input.split('').map(Number); // Convert the input to an array of numbers +}; -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. +// Build the initial disk state (alternating files and free spaces) +const buildDiskState = (diskLengths) => { + let disk = []; + let fileId = 0; + let isFile = true; -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. + for (let length of diskLengths) { + if (isFile) { + disk.push(...Array(length).fill(fileId)); // Add file blocks + fileId++; + } else { + disk.push(...Array(length).fill(-1)); // Add free space blocks + } + isFile = !isFile; // Toggle between file and free space + } -Option one, put a printing press next to the guard's starting position: + return disk; +}; -....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: +// Compact the disk by moving file blocks to the leftmost available free space +const compactDisk = (disk) => { + let moved = true; -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: + while (moved) { + moved = false; -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: + const leftmostFreeIndex = disk.indexOf(-1); + if (leftmostFreeIndex === -1) break; // No free space left to move files into -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: + // Find the last file block's index + let lastFileIndex = disk.length - 1; + while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) { + lastFileIndex--; + } -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: + // If no file blocks to move, stop the process + if (lastFileIndex <= leftmostFreeIndex) break; -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. + // Move the last file block to the leftmost free space + disk[leftmostFreeIndex] = disk[lastFileIndex]; + disk[lastFileIndex] = -1; // Mark the last file block position as free -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); + moved = true; // Continue compacting + } -// Constants for directions and movement offsets -const DIRECTIONS = ['^', '>', 'v', '<']; -const MOVEMENT = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left + return disk; }; -// Read the input file and parse the map -const readInput = (filePath) => { - return fs.readFileSync(filePath, 'utf8').trim().split('\n'); +// Calculate the checksum by summing the product of positions and file IDs +const calculateChecksum = (disk) => { + return disk.reduce((checksum, fileId, index) => { + if (fileId !== -1) { + checksum += index * fileId; // Multiply position by file ID and sum + } + return checksum; + }, 0); }; -// Find the guard's starting position and direction -const findGuard = (map) => { - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - if (DIRECTIONS.includes(map[y][x])) { - return { x, y, direction: map[y][x] }; - } - } - } - throw new Error('Guard not found on the map!'); -}; +// Main function to orchestrate the disk processing and checksum calculation +const processDisk = (filePath) => { + const diskLengths = getInput(filePath); // Step 1: Get and parse the disk map + let disk = buildDiskState(diskLengths); // Step 2: Build the initial disk state -// Turn the guard 90 degrees to the right -const turnRight = (direction) => { - const currentIndex = DIRECTIONS.indexOf(direction); - return DIRECTIONS[(currentIndex + 1) % 4]; -}; + disk = compactDisk(disk); // Step 3: Compact the disk to remove free space -// Get the next position based on the current position and direction -const getNextPosition = (x, y, direction) => { - const { dx, dy } = MOVEMENT[direction]; - return { x: x + dx, y: y + dy }; -}; + const checksum = calculateChecksum(disk); // Step 4: Calculate the checksum -// Check if a position is within the map boundaries -const isWithinBounds = (x, y, map) => { - return x >= 0 && x < map[0].length && y >= 0 && y < map.length; + return checksum; }; -// Check if a position is an obstacle -const isObstacle = (x, y, map) => { - return map[y][x] === '#'; -}; +// Run the function and print the resulting checksum +const checksum = processDisk('input.txt'); +console.log(checksum);",node:14 +2024,9,1,"--- Day 9: Disk Fragmenter --- -// Simulate the guard's movement and check for loops -const simulateGuardMovement = (map, startX, startY, startDirection) => { - let currentDirection = startDirection; - let currentPosition = { x: startX, y: startY }; +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. - const visited = new Set(); - visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`); +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. - while (true) { - const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); +He shows you the disk map (your puzzle input) he's already generated. For example: - // Check if the guard is leaving the map - if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { - return false; // No loop, guard leaves the map - } +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. - // Check if the next position is an obstacle - if (isObstacle(nextPosition.x, nextPosition.y, map)) { - currentDirection = turnRight(currentDirection); // Turn right - } else { - currentPosition = nextPosition; // Move forward - const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`; +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). - // Check if the guard has been here before with the same direction - if (visited.has(key)) { - return true; // Loop detected - } - visited.add(key); - } - } -}; +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: -// Count valid obstruction positions -const countValidObstructionPositions = (map) => { - const { x: startX, y: startY, direction: startDirection } = findGuard(map); - let validPositions = 0; +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - // Skip the guard's starting position and non-empty positions - if ((x === startX && y === startY) || map[y][x] !== '.') { - continue; - } - - // Create a copy of the map with the new obstruction - const newMap = map.map((row) => row.split('')); - newMap[y][x] = '#'; - const newMapString = newMap.map((row) => row.join('')); +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: - // Simulate the guard's movement and check for loops - if (simulateGuardMovement(newMapString, startX, startY, startDirection)) { - validPositions++; - } - } - } +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: - return validPositions; -}; +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. -// Main function to solve the problem -const solve = (filePath) => { - const map = readInput(filePath); - const validPositions = countValidObstructionPositions(map); - console.log(`Number of valid obstruction positions: ${validPositions}`); -}; +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. -// Run the solution -solve('input.txt');",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"const fs = require('fs'); -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +// Load the disk map from the input file +const loadInput = (filePath) => fs.readFileSync(filePath, 'utf8').trim(); -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +// Parse the disk map into blocks +const parseBlocks = (diskMap) => { + const blocks = []; + let isFile = true; + let fileId = 0; -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + for (const char of diskMap) { + const length = parseInt(char, 10); + if (isFile) { + for (let i = 0; i < length; i++) blocks.push(fileId); + fileId++; + } else { + for (let i = 0; i < length; i++) blocks.push(-1); + } + isFile = !isFile; + } -You start by making a map (your puzzle input) of the situation. For example: + return blocks; +}; -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +// Compact the disk by moving file blocks to the leftmost free space +const compactBlocks = (blocks) => { + while (true) { + const freeIndex = blocks.indexOf(-1); + if (freeIndex === -1) break; -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: + let lastFileIndex = blocks.length - 1; + while (lastFileIndex > freeIndex && blocks[lastFileIndex] === -1) lastFileIndex--; -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + if (lastFileIndex <= freeIndex) break; -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: + blocks[freeIndex] = blocks[lastFileIndex]; + blocks[lastFileIndex] = -1; + } -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: + return blocks; +}; -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +// Calculate the checksum of the compacted disk +const computeChecksum = (blocks) => { + return blocks.reduce((sum, block, index) => (block !== -1 ? sum + index * block : sum), 0); +}; -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +// Main function to execute the solution +const main = () => { + const diskMap = loadInput('input.txt'); + const blocks = parseBlocks(diskMap); + const compactedBlocks = compactBlocks(blocks); + const checksum = computeChecksum(compactedBlocks); + console.log(checksum); +}; -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +// Run the program +main();",node:14 +2024,9,1,"--- Day 9: Disk Fragmenter --- -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8'); +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. -// Parse the grid into a 2D array -let grid = input.split('\n').map(line => line.split('')); +He shows you the disk map (your puzzle input) he's already generated. For example: -const numRows = grid.length; -const numCols = grid[0].length; +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. -// Define directions and their corresponding movements -const directions = ['up', 'right', 'down', 'left']; -const moves = { - 'up': [-1, 0], - 'right': [0, 1], - 'down': [1, 0], - 'left': [0, -1] -}; +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). -// Map symbols to directions -const dirSymbols = { - '^': 'up', - '>': 'right', - 'v': 'down', - '<': 'left' -}; +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: -// Find the starting position and direction of the guard -let posRow, posCol, dir; +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: -outerLoop: -for (let i = 0; i < numRows; i++) { - for (let j = 0; j < numCols; j++) { - let cell = grid[i][j]; - if (cell in dirSymbols) { - posRow = i; - posCol = j; - dir = dirSymbols[cell]; - grid[i][j] = '.'; // Replace the starting symbol with empty space - break outerLoop; - } - } -} +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: -// Set to keep track of visited positions -let visited = new Set(); -visited.add(`${posRow},${posCol}`); +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: -while (true) { - // Compute the next position - let [dRow, dCol] = moves[dir]; - let newRow = posRow + dRow; - let newCol = posCol + dCol; +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. - // Check if the guard is about to leave the grid - if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) { - break; - } +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. - let cellAhead = grid[newRow][newCol]; +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"// Read the input disk map as a string +const fs = require('fs'); +const input = fs.readFileSync('input.txt', 'utf-8').trim(); - if (cellAhead === '#') { - // Turn right 90 degrees - let dirIndex = directions.indexOf(dir); - dirIndex = (dirIndex + 1) % 4; - dir = directions[dirIndex]; +// Parse the disk map into file lengths and free space lengths +const diskLengths = input.split('').map(Number); +let disk = []; +let fileId = 0; +let isFile = true; + +// Build the initial disk representation +for (let i = 0; i < diskLengths.length; i++) { + const length = diskLengths[i]; + if (isFile) { + // Add blocks for the current file with the file ID + for (let j = 0; j < length; j++) { + disk.push(fileId); + } + fileId++; } else { - // Move forward - posRow = newRow; - posCol = newCol; - visited.add(`${posRow},${posCol}`); + // Add free space blocks represented by -1 + for (let j = 0; j < length; j++) { + disk.push(-1); + } } + // Alternate between file and free space + isFile = !isFile; } -// Output the number of distinct positions visited -console.log(visited.size);",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- - -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +// Simulate moving file blocks one at a time from the end to the leftmost free space +while (true) { + // Find the leftmost free space index + let leftmostFreeIndex = disk.indexOf(-1); + if (leftmostFreeIndex === -1) { + // No free space left, disk is compacted + break; + } -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + // Find the last file block index + let lastFileIndex = disk.length - 1; + while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) { + lastFileIndex--; + } -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + if (lastFileIndex <= leftmostFreeIndex) { + // No file blocks to move + break; + } -You start by making a map (your puzzle input) of the situation. For example: + // Move the last file block to the leftmost free space + disk[leftmostFreeIndex] = disk[lastFileIndex]; + disk[lastFileIndex] = -1; +} -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +// Calculate the filesystem checksum +let checksum = 0; +for (let i = 0; i < disk.length; i++) { + if (disk[i] !== -1) { + // Sum the product of position and file ID + checksum += i * disk[i]; + } +} -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +// Output the resulting checksum +console.log(checksum);",node:14 +2024,9,2,"--- Day 9: Disk Fragmenter --- -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +He shows you the disk map (your puzzle input) he's already generated. For example: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const map = input.split('\n'); +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: -// Directions: Up, Right, Down, Left -const directions = ['^', '>', 'v', '<']; -let direction = ''; -let position = { x: 0, y: 0 }; +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: -// Parse the map to find the initial position and direction of the guard -for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - if (directions.includes(map[y][x])) { - position = { x, y }; - direction = map[y][x]; - break; - } - } - if (direction) break; -} +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. -// Directions mapping for movement -const movement = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left -}; +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. -// Set to track the visited positions -const visited = new Set(); -visited.add(`${position.x},${position.y}`); +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) -// Function to turn right -const turnRight = (currentDirection) => { - const idx = directions.indexOf(currentDirection); - return directions[(idx + 1) % 4]; -}; +Your puzzle answer was 6421128769094. -let guardRunning = true; +--- Part Two --- -while (guardRunning) { - // Calculate the next position - const nextX = position.x + movement[direction].dx; - const nextY = position.y + movement[direction].dy; +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? - // Check if the next position is outside the map - if ( - nextX < 0 || - nextX >= map[0].length || - nextY < 0 || - nextY >= map.length - ) { - guardRunning = false; // Guard leaves the map - } else { - // Check if the next position is an obstacle - if (map[nextY][nextX] === '#') { - // Turn right - direction = turnRight(direction); - } else { - // Move forward - position.x = nextX; - position.y = nextY; - visited.add(`${position.x},${position.y}`); - } - } -} +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. -console.log(visited.size); // The number of distinct positions visited",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +The first example from above now proceeds differently: -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require('fs'); +const path = require('path'); -You start by making a map (your puzzle input) of the situation. For example: +// Parse the disk map into a memory map array, alternating between files and free space +function parseDiskMap(input) { + if (!input) return []; + + let memoryMap = []; + let isFile = true; + let fileID = 0; + + for (const char of input) { + const length = Number(char); + + if (isNaN(length)) { + console.error(`Invalid character in disk map: ${char}`); + process.exit(1); + } + + if (isFile) { + memoryMap.push(...Array(length).fill(fileID)); + fileID++; + } else { + memoryMap.push(...Array(length).fill(-1)); // Free space + } + + isFile = !isFile; // Alternate between file and free space + } + + return memoryMap; +} + +// Part 2: Compact the disk by moving entire files to the leftmost free space +function compactify2(memoryMap) { + let files = []; + let currentFileID = null; + let currentSize = 0; + + // Extract files from the memory map + for (let i = 0; i <= memoryMap.length; i++) { + const block = memoryMap[i]; + + if (block !== currentFileID && currentFileID !== null) { + files.push({ id: currentFileID, size: currentSize }); + currentFileID = null; + currentSize = 0; + } + + if (block !== -1 && currentFileID === null) { + currentFileID = block; + currentSize = 1; + } else if (block === currentFileID) { + currentSize++; + } + } + + // Sort files by descending ID + files.sort((a, b) => b.id - a.id); + + // Move files to the leftmost available free space + files.forEach(file => { + const { id, size } = file; + let targetStart = -1; + let gapLength = 0; + + // Find the leftmost space for the file + for (let i = 0; i < memoryMap.length; i++) { + if (memoryMap[i] === -1) { + gapLength++; + if (gapLength === size) { + targetStart = i - size + 1; + break; + } + } else { + gapLength = 0; + } + } + + if (targetStart === -1) return; // No space found + + // Move the file blocks to the found space + const filePositions = []; + for (let i = 0; i < memoryMap.length; i++) { + if (memoryMap[i] === id) filePositions.push(i); + } + + if (filePositions.length !== size) { + console.error(`Mismatch in file size for file ID ${id}`); + process.exit(1); + } + + const firstFileBlock = filePositions[0]; + if (firstFileBlock < targetStart) return; // No need to move + + for (let j = 0; j < size; j++) { + memoryMap[targetStart + j] = id; + memoryMap[filePositions[j]] = -1; + } + }); + + return memoryMap; +} + +// Calculate the checksum of the memory map +function calculateChecksum(memoryMap, skipFree = false) { + return memoryMap.reduce((checksum, value, index) => { + if (skipFree && value === -1) return checksum; + if (!skipFree || value !== -1) { + checksum += index * value; + } + return checksum; + }, 0); +} + +// Main function +function main() { + const filePath = path.join(__dirname, 'input.txt'); + + // Read input file + let content; + try { + content = fs.readFileSync(filePath, 'utf-8').trim(); + } catch (err) { + console.error(`Error reading input file: ${err.message}`); + process.exit(1); + } + + // Parse the disk map + const memoryMap = parseDiskMap(content); + + // Prepare separate copies for part 1 and part 2 + const memoryMapPart1 = [...memoryMap]; + const memoryMapPart2 = [...memoryMap]; + + // Part 2: Compact by moving entire files + compactify2(memoryMapPart2); + + // Part 2 Checksum Calculation + const part2Checksum = calculateChecksum(memoryMapPart2, true); + console.log(`Part 2 Checksum: ${part2Checksum}`); +} + +// Execute the program +main();",node:14 +2024,9,2,"--- Day 9: Disk Fragmenter --- + +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) + +Your puzzle answer was 6421128769094. + +--- Part Two --- + +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? + +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. + +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. + +The first example from above now proceeds differently: + +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. + +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require(""fs""); +const inputText = ""./input.txt""; + +fs.readFile(inputText, ""utf8"", (err, data) => { + if (err) { + console.error('Error reading file:', err); + return; + } + + data = data.split("""").map(Number); + + console.log(part1(data)); + console.log(part2(data)); +}); + +const checkSum = data => { + let checkSum = 0; + for (let i = 0; i < data.length; i++) { + if (!isNaN(data[i])) { + checkSum += Number(data[i]) * i; + } + } + return checkSum; +} + +const part1 = (data) => { + let rawData = []; + for (let i = 0; i < data.length; i++) { + const char = i % 2 === 0 + ? (i/2).toString() + : ""."" + rawData.push(...Array(data[i]).fill(char)); + } + + for (let i = 0; i < rawData.length; i++) { + if (rawData[i] === ""."" && rawData[i + 1]) { + if (rawData[rawData.length -1] === ""."") { + while (rawData[rawData.length - 1] === ""."") { + rawData.pop(); + } + } + rawData[i] = rawData.pop(); + } + } + return checkSum(rawData.filter(num => !isNaN(Number(num)))); +} + +const part2 = (data) => { + let rawData = []; + for (let i = 0; i < data.length; i++) { + const char = i % 2 === 0 + ? (i/2).toString() + : ""."" + rawData.push(new Array(data[i]).fill(char)) + } + + if (rawData[rawData.length - 1].includes(""."")) rawData.pop(); + + for (let i = rawData.length - 1; i >= 0; i--) { + if (!rawData[i].length || rawData[i][0] === ""."") continue; + + let firstMatchingIndex = rawData.findIndex((item, index) => item.length >= rawData[i].length && item[0] === ""."" && index < i); + if (firstMatchingIndex === -1) { + continue; + } else { + // if it can be swapped directly, swap it + if (rawData[i].length === rawData[firstMatchingIndex].length) { + [rawData[firstMatchingIndex], rawData[i]] = [rawData[i], rawData[firstMatchingIndex]]; + } else { + const dotsToAdd = new Array(rawData[firstMatchingIndex].length - rawData[i].length).fill("".""); + // i is the numbers, firstMatchingINdex is the dots + let numsToMove = rawData[i]; + rawData[i] = rawData[firstMatchingIndex].slice(0, rawData[i].length); + rawData[firstMatchingIndex] = numsToMove; + rawData.splice(firstMatchingIndex + 1, 0, dotsToAdd); + } + } + } + return checkSum(rawData.flat()); +}",node:14 +2024,9,2,"--- Day 9: Disk Fragmenter --- + +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) + +Your puzzle answer was 6421128769094. + +--- Part Two --- + +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? + +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. + +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. + +The first example from above now proceeds differently: + +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. + +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require('fs'); +const path = require('path'); + +/** + * Parses the disk map string into an array of blocks. + * Files are represented by their unique ID, and free spaces by -1. + * @param {string} input - The disk map string. + * @returns {number[]} - The memory map array. + */ +function parseDiskMap(input) { + if (input === '') { + return []; + } + const memoryMap = []; + let isFile = true; // Flag to alternate between file and free space + let fileID = 0; + + for (const char of input) { + const length = parseInt(char, 10); + if (isNaN(length)) { + console.error(`Invalid character in disk map: ${char}`); + process.exit(1); + } + + if (isFile) { + // Assign fileID to the next 'length' blocks + for (let i = 0; i < length; i++) { + memoryMap.push(fileID); + } + fileID++; + } else { + // Assign -1 (free space) to the next 'length' blocks + for (let i = 0; i < length; i++) { + memoryMap.push(-1); + } + } + + // Toggle between file and free space + isFile = !isFile; + } + + return memoryMap; +} +/** + * Part 2: Move entire files to the leftmost possible free space that can fit them. + * Files are processed in order of decreasing file ID. + * @param {number[]} memoryMap - The memory map array. + * @returns {number[]} - The updated memory map after compaction. + */ +function compactify2(memoryMap) { + // Identify all files with their IDs and sizes + const files = []; + let currentFileID = null; + let currentSize = 0; + + for (let i = 0; i <= memoryMap.length; i++) { + const block = memoryMap[i]; + if (block !== currentFileID && currentFileID !== null) { + // End of the current file + files.push({ id: currentFileID, size: currentSize }); + currentFileID = null; + currentSize = 0; + } + + if (block !== -1 && currentFileID === null) { + // Start of a new file + currentFileID = block; + currentSize = 1; + } else if (block === currentFileID) { + // Continuation of the current file + currentSize++; + } + } + + // Sort files by decreasing file ID + files.sort((a, b) => b.id - a.id); + + for (const file of files) { + const { id, size } = file; + + // Find the leftmost span of free space that can fit the entire file + let targetStart = -1; + let gapLength = 0; + + for (let i = 0; i < memoryMap.length; i++) { + if (memoryMap[i] === -1) { + gapLength++; + if (gapLength === size) { + targetStart = i - size + 1; + break; + } + } else { + gapLength = 0; + } + } + + if (targetStart === -1) { + // No suitable free space found + continue; + } + + // Find the current positions of the file blocks + const filePositions = []; + for (let i = 0; i < memoryMap.length; i++) { + if (memoryMap[i] === id) { + filePositions.push(i); + } + } + + if (filePositions.length !== size) { + console.error(`Mismatch in file size for file ID ${id}`); + process.exit(1); + } + + const firstFileBlock = filePositions[0]; + if (firstFileBlock < targetStart) { + // The file is already to the left; no need to move + continue; + } + + // Move the file blocks to the targetStart + for (let j = 0; j < size; j++) { + memoryMap[targetStart + j] = id; + memoryMap[filePositions[j]] = -1; + } + } + + return memoryMap; +} + +/** + * Calculates the filesystem checksum. + * @param {number[]} memoryMap - The memory map array. + * @param {boolean} skipFree - Whether to skip free spaces (-1). + * @returns {number} - The calculated checksum. + */ +function calculateChecksum(memoryMap, skipFree = false) { + let checksum = 0; + for (let i = 0; i < memoryMap.length; i++) { + const value = memoryMap[i]; + if (skipFree && value === -1) { + continue; + } + if (!skipFree || value !== -1) { + checksum += i * value; + } + } + return checksum; +} + +/** + * Main function to execute the disk compaction and checksum calculation. + */ +function main() { + // Read the input disk map from 'input.txt' + const filePath = path.join(__dirname, 'input.txt'); + let content; + try { + content = fs.readFileSync(filePath, 'utf-8').trim(); + } catch (err) { + console.error(`Error reading input file: ${err.message}`); + process.exit(1); + } + + // Parse the disk map + const memoryMap = parseDiskMap(content); + + // Clone the memory map for Part 1 and Part 2 + const oneMemoryMap = [...memoryMap]; + const twoMemoryMap = [...memoryMap]; + + console.log(`\nInitial Memory Map:`); + console.log(oneMemoryMap.map(block => (block === -1 ? '.' : block)).join('')); + + // Part 2: Compact by moving entire files + console.log(`\n--- Part 2: Moving Entire Files ---`); + console.log(`Started Memory Map Length: ${twoMemoryMap.length}`); + compactify2(twoMemoryMap); + console.log(`Ended Memory Map Length: ${twoMemoryMap.length}`); + console.log(`Final Memory Map after Part 2:`); + console.log(twoMemoryMap.map(block => (block === -1 ? '.' : block)).join('')); + + // Calculate Part 2 Checksum + let sumPart2 = 0; + for (let pos = 0; pos < twoMemoryMap.length; pos++) { + const value = twoMemoryMap[pos]; + if (value === -1) { + continue; // Skip free spaces + } + sumPart2 += pos * value; + } + console.log(`Part 2 Checksum: ${sumPart2}`); +} + +// Execute the main function +main();",node:14 +2024,9,2,"--- Day 9: Disk Fragmenter --- + +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) + +Your puzzle answer was 6421128769094. + +--- Part Two --- + +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? + +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. + +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. + +The first example from above now proceeds differently: + +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. + +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require(""fs""); +const inputText = ""./input.txt""; + +// Asynchronous file reading and processing +const processFile = (filePath) => { + fs.readFile(filePath, ""utf8"", (err, data) => { + if (err) { + console.error(""Error reading file:"", err); + return; + } + + const parsedData = parseInputData(data); + console.log(computePart1(parsedData)); + console.log(computePart2(parsedData)); + }); +}; + +// Parse the input data into an array of numbers +const parseInputData = (data) => { + return data.split("""").map(Number); +}; + +// Helper function to compute checksum +const calculateChecksum = (data) => { + return data.reduce((sum, value, index) => { + if (!isNaN(value)) { + return sum + value * index; + } + return sum; + }, 0); +}; + +// Part 1 computation logic +const computePart1 = (data) => { + let rawData = createInitialRawData(data); + + // Perform the file-block shifting logic + rawData = moveFileBlocks(rawData); + + // Filter out non-numeric values and calculate checksum + const numericData = rawData.filter(value => !isNaN(Number(value))); + return calculateChecksum(numericData); +}; + +// Helper function to create the initial raw data +const createInitialRawData = (data) => { + let rawData = []; + for (let i = 0; i < data.length; i++) { + const char = i % 2 === 0 ? (i / 2).toString() : "".""; + rawData.push(...Array(data[i]).fill(char)); + } + return rawData; +}; + +// Helper function to shift file blocks +const moveFileBlocks = (rawData) => { + for (let i = 0; i < rawData.length; i++) { + if (rawData[i] === ""."" && rawData[i + 1]) { + if (rawData[rawData.length - 1] === ""."") { + while (rawData[rawData.length - 1] === ""."") { + rawData.pop(); + } + } + rawData[i] = rawData.pop(); + } + } + return rawData; +}; + +// Part 2 computation logic +const computePart2 = (data) => { + let rawData = create2DInitialRawData(data); + + // Remove unnecessary trailing empty slots + if (rawData[rawData.length - 1].includes(""."")) rawData.pop(); + + // Perform file swapping and shifting + rawData = swapAndShiftFiles(rawData); + + // Flatten the 2D array and calculate checksum + return calculateChecksum(rawData.flat()); +}; + +// Helper function to create the initial 2D raw data for part 2 +const create2DInitialRawData = (data) => { + let rawData = []; + for (let i = 0; i < data.length; i++) { + const char = i % 2 === 0 ? (i / 2).toString() : "".""; + rawData.push(new Array(data[i]).fill(char)); + } + return rawData; +}; + +// Helper function to swap and shift file blocks +const swapAndShiftFiles = (rawData) => { + for (let i = rawData.length - 1; i >= 0; i--) { + if (!rawData[i].length || rawData[i][0] === ""."") continue; + + const firstMatchingIndex = findMatchingFreeSpace(rawData, i); + if (firstMatchingIndex === -1) continue; + + if (rawData[i].length === rawData[firstMatchingIndex].length) { + [rawData[firstMatchingIndex], rawData[i]] = [rawData[i], rawData[firstMatchingIndex]]; + } else { + const dotsToAdd = new Array(rawData[firstMatchingIndex].length - rawData[i].length).fill("".""); + let numsToMove = rawData[i]; + rawData[i] = rawData[firstMatchingIndex].slice(0, rawData[i].length); + rawData[firstMatchingIndex] = numsToMove; + rawData.splice(firstMatchingIndex + 1, 0, dotsToAdd); + } + } + return rawData; +}; + +// Helper function to find the first matching free space large enough to fit a file +const findMatchingFreeSpace = (rawData, currentIndex) => { + return rawData.findIndex((item, index) => item.length >= rawData[currentIndex].length && item[0] === ""."" && index < currentIndex); +}; + +// Execute the program +processFile(inputText);",node:14 +2024,9,2,"--- Day 9: Disk Fragmenter --- + +Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. + +While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. + +He shows you the disk map (your puzzle input) he's already generated. For example: + +2333133121414131402 +The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + +So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + +Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + +0..111....22222 +The first example above, 2333133121414131402, represents these individual blocks: + +00...111...2...333.44.5555.6666.777.888899 +The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: + +0..111....22222 +02.111....2222. +022111....222.. +0221112...22... +02211122..2.... +022111222...... +The first example requires a few more steps: + +00...111...2...333.44.5555.6666.777.888899 +009..111...2...333.44.5555.6666.777.88889. +0099.111...2...333.44.5555.6666.777.8888.. +00998111...2...333.44.5555.6666.777.888... +009981118..2...333.44.5555.6666.777.88.... +0099811188.2...333.44.5555.6666.777.8..... +009981118882...333.44.5555.6666.777....... +0099811188827..333.44.5555.6666.77........ +00998111888277.333.44.5555.6666.7......... +009981118882777333.44.5555.6666........... +009981118882777333644.5555.666............ +00998111888277733364465555.66............. +0099811188827773336446555566.............. +The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. + +Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. + +Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) + +Your puzzle answer was 6421128769094. + +--- Part Two --- + +Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? + +The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. + +This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. + +The first example from above now proceeds differently: + +00...111...2...333.44.5555.6666.777.888899 +0099.111...2...333.44.5555.6666.777.8888.. +0099.1117772...333.44.5555.6666.....8888.. +0099.111777244.333....5555.6666.....8888.. +00992111777.44.333....5555.6666.....8888.. +The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. + +Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require(""fs""); +const inputText = ""./input.txt""; + +// Read the input file and handle errors +function readInputFile(filePath) { + return new Promise((resolve, reject) => { + fs.readFile(filePath, ""utf8"", (err, data) => { + if (err) { + reject(`Error reading file: ${err}`); + } else { + resolve(data); + } + }); + }); +} + +// Helper function to calculate the checksum +function calculateChecksum(data) { + return data.reduce((checksum, value, index) => { + if (!isNaN(value)) { + checksum += Number(value) * index; + } + return checksum; + }, 0); +} + +// Part 1 logic: Process data into a new array, then calculate checksum +function processPart1(data) { + const rawData = []; + + data.forEach((value, index) => { + const char = index % 2 === 0 ? (index / 2).toString() : "".""; + rawData.push(...Array(value).fill(char)); + }); + + // Cleanup rawData by removing trailing dots and adjusting positions + for (let i = 0; i < rawData.length; i++) { + if (rawData[i] === ""."" && rawData[i + 1]) { + if (rawData[rawData.length - 1] === ""."") { + while (rawData[rawData.length - 1] === ""."") { + rawData.pop(); + } + } + rawData[i] = rawData.pop(); + } + } + + return calculateChecksum(rawData.filter(num => !isNaN(Number(num)))); +} + +// Part 2 logic: Compact the array by moving file blocks to free space +function processPart2(data) { + const rawData = []; + + data.forEach((value, index) => { + const char = index % 2 === 0 ? (index / 2).toString() : "".""; + rawData.push(new Array(value).fill(char)); + }); + + if (rawData[rawData.length - 1].includes(""."")) rawData.pop(); + + // Move files into the leftmost available spaces + for (let i = rawData.length - 1; i >= 0; i--) { + if (!rawData[i].length || rawData[i][0] === ""."") continue; + + const firstMatchingIndex = rawData.findIndex((item, index) => { + return item.length >= rawData[i].length && item[0] === ""."" && index < i; + }); + + if (firstMatchingIndex !== -1) { + if (rawData[i].length === rawData[firstMatchingIndex].length) { + [rawData[firstMatchingIndex], rawData[i]] = [rawData[i], rawData[firstMatchingIndex]]; + } else { + const dotsToAdd = new Array(rawData[firstMatchingIndex].length - rawData[i].length).fill("".""); + const numsToMove = rawData[i]; + rawData[i] = rawData[firstMatchingIndex].slice(0, rawData[i].length); + rawData[firstMatchingIndex] = numsToMove; + rawData.splice(firstMatchingIndex + 1, 0, dotsToAdd); + } + } + } + + return calculateChecksum(rawData.flat()); +} + +// Main function to execute the program +async function main() { + try { + const data = await readInputFile(inputText); + const parsedData = data.split("""").map(Number); + + console.log(""Part 1 Checksum:"", processPart1(parsedData)); + console.log(""Part 2 Checksum:"", processPart2(parsedData)); + } catch (error) { + console.error(error); + } +} + +// Run the main function +main();",node:14 +2024,10,1,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"const fs = require('fs'); + +class Position { + constructor(row, col, height) { + this.row = row; + this.col = col; + this.height = height; + } + + toString() { + return `${this.row},${this.col}`; + } +} + +class HikingMap { + constructor(grid) { + this.grid = grid; + this.rows = grid.length; + this.cols = grid[0].length; + this.directions = [ + { dx: 0, dy: 1 }, // right + { dx: 1, dy: 0 }, // down + { dx: 0, dy: -1 }, // left + { dx: -1, dy: 0 } // up + ]; + } + + getHeight(row, col) { + return this.grid[row][col]; + } + + isValidPosition(row, col) { + return row >= 0 && row < this.rows && col >= 0 && col < this.cols; + } + + findTrailheads() { + const trailheads = []; + for (let row = 0; row < this.rows; row++) { + for (let col = 0; col < this.cols; col++) { + if (this.getHeight(row, col) === 0) { + trailheads.push(new Position(row, col, 0)); + } + } + } + return trailheads; + } + + getNeighbors(position) { + return this.directions + .map(({ dx, dy }) => ({ + row: position.row + dx, + col: position.col + dy + })) + .filter(({ row, col }) => this.isValidPosition(row, col)) + .map(({ row, col }) => new Position(row, col, this.getHeight(row, col))); + } +} + +class TrailFinder { + constructor(hikingMap) { + this.map = hikingMap; + this.reachableNines = new Set(); + this.visited = new Set(); + } + + findTrailsFromPosition(position) { + this.reachableNines.clear(); + this.visited.clear(); + this.visited.add(position.toString()); + this.explorePaths(position); + return this.reachableNines.size; + } + + explorePaths(currentPos) { + if (currentPos.height === 9) { + this.reachableNines.add(currentPos.toString()); + return; + } + + const neighbors = this.map.getNeighbors(currentPos); + + for (const neighbor of neighbors) { + const key = neighbor.toString(); + + if (!this.visited.has(key) && neighbor.height === currentPos.height + 1) { + this.visited.add(key); + this.explorePaths(neighbor); + this.visited.delete(key); + } + } + } +} + +class HikingTrailSolver { + static solve(inputFile) { + try { + const grid = this.parseInput(inputFile); + const hikingMap = new HikingMap(grid); + const trailFinder = new TrailFinder(hikingMap); + + return hikingMap.findTrailheads() + .map(trailhead => trailFinder.findTrailsFromPosition(trailhead)) + .reduce((sum, score) => sum + score, 0); + } catch (error) { + console.error('Error solving hiking trails:', error); + throw error; + } + } + + static parseInput(filename) { + const content = fs.readFileSync(filename, 'utf8').trim(); + return content.split('\n').map(line => + line.split('').map(Number) + ); + } +} + +// Execute solution +try { + const result = HikingTrailSolver.solve('input.txt'); + console.log(`Sum of trailhead scores: ${result}`); +} catch (error) { + console.error('Failed to solve puzzle:', error); + process.exit(1); +}",node:14 +2024,10,1,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"const fs = require('fs'); + +function findTrailheadScores(map) { + const rows = map.length; + const cols = map[0].length; + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up + let totalScore = 0; + + // Find all trailheads (positions with height 0) + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (map[r][c] === 0) { + const score = calculateTrailheadScore(r, c, map); + totalScore += score; + } + } + } + + return totalScore; +} + +function calculateTrailheadScore(startRow, startCol, map) { + const rows = map.length; + const cols = map[0].length; + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; + const reachableNines = new Set(); // Store unique positions of reachable 9s + + // Use DFS to find all possible paths + function dfs(row, col, currentHeight, visited) { + // If we reached height 9, add position to reachableNines + if (map[row][col] === 9) { + reachableNines.add(`${row},${col}`); + return; + } + + // Try all directions + for (const [dr, dc] of directions) { + const newRow = row + dr; + const newCol = col + dc; + + // Check if new position is valid + if (newRow >= 0 && newRow < rows && + newCol >= 0 && newCol < cols && + !visited.has(`${newRow},${newCol}`)) { + + // Check if height increases by exactly 1 + if (map[newRow][newCol] === currentHeight + 1) { + visited.add(`${newRow},${newCol}`); + dfs(newRow, newCol, currentHeight + 1, visited); + visited.delete(`${newRow},${newCol}`); + } + } + } + } + + // Start DFS from the trailhead + const visited = new Set([`${startRow},${startCol}`]); + dfs(startRow, startCol, 0, visited); + + return reachableNines.size; +} + +// Read and parse input +function parseInput(filename) { + const input = fs.readFileSync(filename, 'utf8').trim(); + return input.split('\n').map(line => + line.split('').map(Number) + ); +} + +// Main execution +try { + const map = parseInput('input.txt'); + const result = findTrailheadScores(map); + console.log(`Sum of trailhead scores: ${result}`); +} catch (error) { + console.error('Error:', error.message); +}",node:14 +2024,10,1,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"const fs = require('fs'); + +// Function to parse the input map into a 2D array of integers +const parseInput = (filename) => { + try { + const input = fs.readFileSync(filename, 'utf8').trim(); + return input.split('\n').map(line => line.split('').map(Number)); + } catch (error) { + console.error('Error parsing input:', error.message); + throw error; + } +}; + +// Helper function to check if a given position is within bounds and valid for hiking +const isValidMove = (row, col, currentHeight, rows, cols, visited, map) => { + return ( + row >= 0 && row < rows && + col >= 0 && col < cols && + !visited.has(`${row},${col}`) && + map[row][col] === currentHeight + 1 + ); +}; + +// Depth First Search (DFS) to explore hiking trails from a given start position +const dfs = (row, col, currentHeight, visited, rows, cols, directions, map, reachableNines) => { + if (map[row][col] === 9) { + reachableNines.add(`${row},${col}`); + return; + } + + // Explore in all 4 directions (right, down, left, up) + for (const [dr, dc] of directions) { + const newRow = row + dr; + const newCol = col + dc; + + if (isValidMove(newRow, newCol, currentHeight, rows, cols, visited, map)) { + visited.add(`${newRow},${newCol}`); + dfs(newRow, newCol, currentHeight + 1, visited, rows, cols, directions, map, reachableNines); + visited.delete(`${newRow},${newCol}`); + } + } +}; + +// Function to calculate the score of a trailhead +const calculateTrailheadScore = (startRow, startCol, map) => { + const rows = map.length; + const cols = map[0].length; + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up + const reachableNines = new Set(); // Store unique positions of reachable 9s + const visited = new Set([`${startRow},${startCol}`]); // Initialize visited set with the trailhead + + // Start DFS to explore hiking paths from the trailhead + dfs(startRow, startCol, 0, visited, rows, cols, directions, map, reachableNines); + + return reachableNines.size; // Return the number of reachable '9' heights +}; + +// Function to find the sum of trailhead scores on the map +const findTrailheadScores = (map) => { + const rows = map.length; + const cols = map[0].length; + let totalScore = 0; + + // Loop through each position on the map to find trailheads (height 0) + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (map[r][c] === 0) { // Found a trailhead + totalScore += calculateTrailheadScore(r, c, map); // Add score from this trailhead + } + } + } + + return totalScore; +}; + +// Main function to execute the program +const main = () => { + const map = parseInput('input.txt'); // Read and parse the map + const result = findTrailheadScores(map); // Calculate the sum of trailhead scores + console.log(`Sum of trailhead scores: ${result}`); // Output the result +}; + +main();",node:14 +2024,10,1,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"const fs = require('fs'); + +// Step 1: Parse the Input +const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n').map(line => line.split('').map(Number)); +const numRows = input.length; +const numCols = input[0].length; + +// Directions: up, down, left, right +const dirs = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1] +]; + +// Step 2: Identify Trailheads +const trailheads = []; +for (let i = 0; i < numRows; i++) { + for (let j = 0; j < numCols; j++) { + if (input[i][j] === 0) { + trailheads.push([i, j]); + } + } +} + +// Step 3: DFS to find reachable 9s +function dfs(x, y, currentHeight, visited) { + if (currentHeight === 9) { + return new Set([[x, y].toString()]); + } + let reachable = new Set(); + for (const [dx, dy] of dirs) { + const nx = x + dx; + const ny = y + dy; + if ( + nx >= 0 && nx < numRows && + ny >= 0 && ny < numCols && + input[nx][ny] === currentHeight + 1 && + !visited.has([nx, ny].toString()) + ) { + visited.add([nx, ny].toString()); + const result = dfs(nx, ny, input[nx][ny], visited); + for (const pos of result) { + reachable.add(pos); + } + } + } + return reachable; +} + +// Step 4 & 5: Calculate Scores and Sum +let totalScore = 0; +for (const [i, j] of trailheads) { + const reachable9s = dfs(i, j, 0, new Set([`${i},${j}`])); + totalScore += reachable9s.size; +} + +console.log(totalScore);",node:14 +2024,10,1,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"const fs = require(""fs""); + +// Constants +const DIRECTIONS = [ + [0, 1], // Right + [1, 0], // Down + [0, -1], // Left + [-1, 0], // Up +]; + +// Helper function to parse the input file into a 2D map +const parseInput = (filename) => { + const input = fs.readFileSync(filename, ""utf8"").trim(); + return input.split(""\n"").map((line) => line.split("""").map(Number)); +}; + +// Helper function to check if a position is valid on the map +const isValidPosition = (row, col, rows, cols) => { + return row >= 0 && row < rows && col >= 0 && col < cols; +}; + +// Depth-First Search (DFS) to find reachable 9s from a trailhead +const dfs = (row, col, currentHeight, map, visited, reachableNines) => { + const rows = map.length; + const cols = map[0].length; + + // If we reach a height of 9, add it to the reachableNines set + if (map[row][col] === 9) { + reachableNines.add(`${row},${col}`); + return; + } + + // Explore all four directions + for (const [dr, dc] of DIRECTIONS) { + const newRow = row + dr; + const newCol = col + dc; + + // Check if the new position is valid and not visited + if (isValidPosition(newRow, newCol, rows, cols) && !visited.has(`${newRow},${newCol}`)) { + // Ensure the height increases by exactly 1 + if (map[newRow][newCol] === currentHeight + 1) { + visited.add(`${newRow},${newCol}`); + dfs(newRow, newCol, currentHeight + 1, map, visited, reachableNines); + visited.delete(`${newRow},${newCol}`); + } + } + } +}; + +// Calculate the score for a single trailhead +const calculateTrailheadScore = (startRow, startCol, map) => { + const reachableNines = new Set(); // Track unique positions of reachable 9s + const visited = new Set([`${startRow},${startCol}`]); // Track visited positions + + // Perform DFS to find all reachable 9s + dfs(startRow, startCol, 0, map, visited, reachableNines); + + return reachableNines.size; // The score is the number of unique reachable 9s +}; + +// Find the sum of scores for all trailheads on the map +const findTrailheadScores = (map) => { + const rows = map.length; + const cols = map[0].length; + let totalScore = 0; + + // Iterate through the map to find all trailheads (height 0) + for (let r = 0; r < rows; r++) { + for (let c = 0; c < cols; c++) { + if (map[r][c] === 0) { + const score = calculateTrailheadScore(r, c, map); + totalScore += score; + } + } + } + + return totalScore; +}; + +// Main function to execute the program +const main = () => { + try { + const map = parseInput(""input.txt""); // Parse the input file + const result = findTrailheadScores(map); // Calculate the total score + console.log(`Sum of trailhead scores: ${result}`); + } catch (error) { + console.error(""Error:"", error.message); + } +}; + +// Run the program +main();",node:14 +2024,10,2,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"const fs = require(""fs""); +const inputText = ""./input.txt""; + +fs.readFile(inputText, ""utf8"", (err, data) => { + if (err) { + console.error('Error reading file:', err); + return; + } + + console.log(""Part 1:"", getTotalValidTrails(data)); + console.log(""Part 2:"", getTotalValidTrails(data, true)); +}); + +const getZeroLocations = data => { + const zeroLocations = []; + for (let i = 0; i < data.length; i++) { + const line = data[i]; + for (let j = 0; j < line.length; j++) { + const item = line[j]; + if (item === 0) { + zeroLocations.push([i, j]); + } + } + } + return zeroLocations; +} + +const getValidTrails = (mapArr, startLocation, cumulative) => { + const directions = [[-1, 0], [0, -1], [1, 0],[0, 1]]; + const visited = new Set(); + let validTrails = 0; + const queue = [startLocation]; + if (!cumulative) visited.add(`${startLocation[0]}, ${startLocation[1]}`) + + while (queue.length > 0) { + const [currX, currY] = queue.shift(); + if (mapArr[currX][currY] === 9) { + validTrails++; + } + + for (let [dx, dy] of directions) { + const nextX = currX + dx; + const nextY = currY + dy; + + // Check if next coord is within the map + if (nextX >= 0 && nextY >= 0 && nextX < mapArr.length && nextY < mapArr[0].length) { + if (mapArr[nextX][nextY] !== (mapArr[currX][currY] + 1)) continue; + const nextCoordStr = `${nextX}, ${nextY}`; + // Part2 is cumulative, part1 requires that this coord has not yet been visited + if (cumulative || !visited.has(nextCoordStr)) { + queue.push([nextX, nextY]); + visited.add(nextCoordStr); + } + } + } + } + return validTrails; +} + +const getTotalValidTrails = (data, cumulative) => { + let totalValidTrails = 0; + const mapArr = data.split(""\n"").map(line => line.split("""").map(Number)); + const zeros = getZeroLocations(mapArr); + + for (let zero of zeros) { + const validTrails = getValidTrails(mapArr, zero, cumulative); + totalValidTrails += validTrails; + } + return totalValidTrails; +}",node:14 +2024,10,2,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"const fs = require('fs'); + +class HikingTrails { + constructor(grid) { + this.grid = grid; + this.rows = grid.length; + this.cols = grid[0].length; + this.directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up + } + + findTrailheadRatings() { + let totalRating = 0; + + // Find all trailheads (height 0) + for (let r = 0; r < this.rows; r++) { + for (let c = 0; c < this.cols; c++) { + if (this.grid[r][c] === 0) { + const rating = this.calculateTrailheadRating(r, c); + totalRating += rating; + } + } + } + + return totalRating; + } + + calculateTrailheadRating(startRow, startCol) { + const paths = new Set(); + const visited = new Set(); + + const buildPath = (path) => { + return path.join(','); + }; + + const dfs = (row, col, currentHeight, currentPath) => { + // If we reached height 9, we found a complete path + if (this.grid[row][col] === 9) { + paths.add(buildPath(currentPath)); + return; + } + + // Try all directions + for (const [dr, dc] of this.directions) { + const newRow = row + dr; + const newCol = col + dc; + const newPos = `${newRow},${newCol}`; + + if (this.isValidMove(newRow, newCol) && + !visited.has(newPos) && + this.grid[newRow][newCol] === currentHeight + 1) { + + visited.add(newPos); + currentPath.push(newPos); + + dfs(newRow, newCol, currentHeight + 1, currentPath); + + visited.delete(newPos); + currentPath.pop(); + } + } + }; + + // Start DFS from the trailhead + const startPos = `${startRow},${startCol}`; + visited.add(startPos); + dfs(startRow, startCol, 0, [startPos]); + + return paths.size; + } + + isValidMove(row, col) { + return row >= 0 && row < this.rows && col >= 0 && col < this.cols; + } +} + +function parseInput(filename) { + try { + const input = fs.readFileSync(filename, 'utf8').trim(); + return input.split('\n').map(line => + line.split('').map(Number) + ); + } catch (error) { + console.error('Error reading input file:', error); + process.exit(1); + } +} + +function solve(filename) { + const grid = parseInput(filename); + const hikingTrails = new HikingTrails(grid); + return hikingTrails.findTrailheadRatings(); +} + +// Execute solution +try { + const result = solve('input.txt'); + console.log(`Sum of trailhead ratings: ${result}`); +} catch (error) { + console.error('Error:', error); + process.exit(1); +}",node:14 +2024,10,2,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"const fs = require('fs'); + +class HikingTrails { + constructor(grid) { + this.grid = grid; + this.rows = grid.length; + this.cols = grid[0].length; + this.directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up + } + + // Main function to compute the sum of trailhead ratings + calculateTotalTrailheadRatings() { + let totalRating = 0; + + for (let r = 0; r < this.rows; r++) { + for (let c = 0; c < this.cols; c++) { + if (this.grid[r][c] === 0) { // Found a trailhead + totalRating += this.calculateTrailheadRating(r, c); + } + } + } + + return totalRating; + } + + // Calculate the rating for a specific trailhead (height 0) + calculateTrailheadRating(startRow, startCol) { + const paths = new Set(); // Store unique paths + const visited = new Set(); // Store visited positions + + const dfs = (row, col, currentHeight, currentPath) => { + // If we reached height 9, we found a valid path + if (this.grid[row][col] === 9) { + paths.add(currentPath.join(',')); // Store path as a string + return; + } + + // Explore all four possible directions (right, down, left, up) + for (const [dr, dc] of this.directions) { + const newRow = row + dr; + const newCol = col + dc; + const newPos = `${newRow},${newCol}`; + + if (this.isValidMove(newRow, newCol) && + !visited.has(newPos) && + this.grid[newRow][newCol] === currentHeight + 1) { + + visited.add(newPos); + currentPath.push(newPos); + + // Continue DFS + dfs(newRow, newCol, currentHeight + 1, currentPath); + + visited.delete(newPos); // Backtrack + currentPath.pop(); + } + } + }; + + // Start DFS from the trailhead + const startPos = `${startRow},${startCol}`; + visited.add(startPos); + dfs(startRow, startCol, 0, [startPos]); + + return paths.size; // Return number of unique paths to height 9 + } + + // Check if a position is within bounds + isValidMove(row, col) { + return row >= 0 && row < this.rows && col >= 0 && col < this.cols; + } +} + +// Read and parse the input file into a 2D grid +const parseInput = (filename) => { + try { + const input = fs.readFileSync(filename, 'utf8').trim(); + return input.split('\n').map(line => + line.split('').map(Number) // Convert each character to a number + ); + } catch (error) { + console.error('Error reading input file:', error); + process.exit(1); + } +}; + +// Solve the problem and return the result +const solve = (filename) => { + const grid = parseInput(filename); + const hikingTrails = new HikingTrails(grid); + return hikingTrails.calculateTotalTrailheadRatings(); +}; + +// Main execution +try { + const result = solve('input.txt'); + console.log(`Sum of trailhead ratings: ${result}`); +} catch (error) { + console.error('Error:', error); + process.exit(1); +}",node:14 +2024,10,2,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"const fs = require('fs'); +const {log} = require('console'); + +const lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); + +const trailheads = []; + +for (let r = 0; r < lines.length; r++) { + for (let c = 0; c < lines[r].length; c++) { + if (lines[r][c] === '0') { + trailheads.push([c, r]); + } + } +} + +const directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]; + +function isInBounds(nextC, nextR) { + return nextC >= 0 && nextR >= 0 && nextC < lines[0].length && nextR < lines.length; +} + +function getScore(trailhead, distinct) { + let score = []; + let queue = directions.map(d => [...trailhead, trailhead[0] + d[0], trailhead[1] + d[1]]); + while (queue.length > 0) { + let [c, r, nextC, nextR] = queue.shift(); + if (isInBounds(nextC, nextR) && parseInt(lines[nextR][nextC]) - parseInt(lines[r][c]) === 1) { + if (lines[nextR][nextC] === '9') { + score.push(`${nextC}-${nextR}`); + } else { + directions.forEach(d => queue.push([nextC, nextR, nextC + d[0], nextR + d[1]])) + } + } + } + if (distinct) { + return score.length; + } else { + return new Set(score).size; + } +} + +let part1 = 0; +for (let trailhead of trailheads) { + part1 += getScore(trailhead, false); +} +log(part1); + +let part2 = 0; +for (let trailhead of trailheads) { + part2 += getScore(trailhead, true); +} +log(part2);",node:14 +2024,10,2,"--- Day 10: Hoof It --- + +You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + +The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + +Perhaps you can help fill in the missing hiking trails? + +The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + +0123 +1234 +8765 +9876 +Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). + +You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + +A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + +This trailhead has a score of 2: + +...0... +...1... +...2... +6543456 +7.....7 +8.....8 +9.....9 +(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + +This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + +10..9.. +2...8.. +3...7.. +4567654 +...8..3 +...9..2 +.....01 +Here's a larger example: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + +The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + +Your puzzle answer was 587. + +--- Part Two --- + +The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + +The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + +.....0. +..4321. +..5..2. +..6543. +..7..4. +..8765. +..9.... +The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + +.....0. .....0. .....0. +..4321. .....1. .....1. +..5.... .....2. .....2. +..6.... ..6543. .....3. +..7.... ..7.... .....4. +..8.... ..8.... ..8765. +..9.... ..9.... ..9.... +Here is a map containing a single trailhead with rating 13: + +..90..9 +...1.98 +...2..7 +6543456 +765.987 +876.... +987.... +This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + +012345 +123456 +234567 +345678 +4.6789 +56789. +Here's the larger example from before: + +89010123 +78121874 +87430965 +96549874 +45678903 +32019012 +01329801 +10456732 +Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + +You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"const fs = require('fs'); + +// Step 1: Parse the Input +const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n').map(line => line.split('').map(Number)); +const numRows = input.length; +const numCols = input[0].length; + +// Directions: up, down, left, right +const dirs = [ + [-1, 0], + [1, 0], + [0, -1], + [0, 1] +]; + +// Step 2: Identify Trailheads +const trailheads = []; +for (let i = 0; i < numRows; i++) { + for (let j = 0; j < numCols; j++) { + if (input[i][j] === 0) { + trailheads.push([i, j]); + } + } +} + +// Step 3: Memoization Map +const memo = Array.from({ length: numRows }, () => Array(numCols).fill(null)); + +// Step 4: DFS to count distinct trails +function countTrails(x, y) { + if (input[x][y] === 9) { + return 1; + } + if (memo[x][y] !== null) { + return memo[x][y]; + } + let totalPaths = 0; + for (const [dx, dy] of dirs) { + const nx = x + dx; + const ny = y + dy; + if ( + nx >= 0 && nx < numRows && + ny >= 0 && ny < numCols && + input[nx][ny] === input[x][y] + 1 + ) { + totalPaths += countTrails(nx, ny); + } + } + memo[x][y] = totalPaths; + return totalPaths; +} + +// Step 5 & 6: Calculate Ratings and Sum +let totalRating = 0; +for (const [i, j] of trailheads) { + totalRating += countTrails(i, j); +} + +console.log(totalRating);",node:14 +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"const fs = require('fs'); + +class PlutonianPebbles { + constructor(stones) { + this.stones = stones; + } + + // Perform one blink operation on the stones + blink() { + const newStones = this.stones.reduce((acc, stone) => { + if (stone === 0) { + acc.push(1); + } else if (this.hasEvenDigits(stone)) { + const digits = String(stone); + const mid = Math.floor(digits.length / 2); + const left = parseInt(digits.slice(0, mid)); + const right = parseInt(digits.slice(mid)); + acc.push(left, right); + } else { + acc.push(stone * 2024); + } + return acc; + }, []); + + this.stones = newStones; + return this.stones.length; + } + + // Check if a number has an even number of digits + hasEvenDigits(num) { + return String(num).length % 2 === 0; + } + + // Simulate a number of blink operations and return the final stone count + simulateBlinks(count) { + let stoneCount; + for (let i = 0; i < count; i++) { + stoneCount = this.blink(); + } + return stoneCount; + } +} + +// Function to read and parse the input file +function parseInput(filename) { + const input = fs.readFileSync(filename, 'utf8').trim(); + return input.split(/\s+/).map(Number); +} + +// Main logic to solve the problem +function solve(filename) { + const initialStones = parseInput(filename); + const pebbles = new PlutonianPebbles(initialStones); + return pebbles.simulateBlinks(25); +} + +// Execution block +try { + const result = solve('input.txt'); + console.log(`Number of stones after 25 blinks: ${result}`); +} catch (error) { + console.error('Error:', error); + process.exit(1); +}",node:14 +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"const fs = require('fs'); + +let stones = fs.readFileSync('input.txt', 'utf-8').trim().split(/\s+/); + +const blinks = 25; + +for (let i = 0; i < blinks; i++) { + let newStones = []; + for (let stone of stones) { + if (stone === '0') { + newStones.push('1'); + } else if (stone.length % 2 === 0) { + let half = stone.length / 2; + let left = stone.slice(0, half).replace(/^0+/, '') || '0'; + let right = stone.slice(half).replace(/^0+/, '') || '0'; + newStones.push(left, right); + } else { + let num = BigInt(stone); + let newNum = num * 2024n; + newStones.push(newNum.toString()); + } + } + stones = newStones; +} + +console.log(stones.length);",node:14 +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"const fs = require('fs'); + +class PlutonianPebbles { + constructor(stones) { + this.stones = stones; + } + + blink() { + let newStones = []; + for (const stone of this.stones) { + if (stone === 0) { + newStones.push(1); + } else if (this.hasEvenDigits(stone)) { + const digits = String(stone); + const mid = Math.floor(digits.length / 2); + const left = parseInt(digits.slice(0, mid)); + const right = parseInt(digits.slice(mid)); + newStones.push(left, right); + } else { + newStones.push(stone * 2024); + } + } + this.stones = newStones; + return this.stones.length; + } + + hasEvenDigits(num) { + return String(num).length % 2 === 0; + } + + simulateBlinks(count) { + let stoneCount; + for (let i = 0; i < count; i++) { + stoneCount = this.blink(); + } + return stoneCount; + } +} + +function solve(filename) { + const input = fs.readFileSync(filename, 'utf8').trim(); + const initialStones = input.split(/\s+/).map(Number); + const pebbles = new PlutonianPebbles(initialStones); + return pebbles.simulateBlinks(25); +} + +try { + const result = solve('input.txt'); + console.log(`Number of stones after 25 blinks: ${result}`); +} catch (error) { + console.error('Error:', error); + process.exit(1); +}",node:14 +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"const fs = require(""fs""); + +// Function to apply transformation rules to a single stone +const applyTransformation = (stone) => { + if (stone === 0) return [1]; + const numDigits = String(stone).length; + if (numDigits % 2 === 0) { + const half = numDigits / 2; + const left = parseInt(String(stone).slice(0, half)); + const right = parseInt(String(stone).slice(half)); + return [left, right]; + } + return [stone * 2024]; +}; + +// Function to simulate blinking for all stones +const simulateBlinking = (stones, blinks) => { + for (let i = 0; i < blinks; i++) { + stones = stones.flatMap(applyTransformation); + } + return stones; +}; + +// Main function to read input, simulate blinking, and output the result +const main = () => { + const input = fs.readFileSync(""input.txt"", ""utf8"").trim(); + let stones = input.split("" "").map(Number); + + const finalStones = simulateBlinking(stones, 25); + console.log(finalStones.length); +}; + +// Execute the program +main();",node:14 +2024,11,1,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times?",193607,"const fs = require(""fs""); + +const transformStone = (stone) => { + if (stone === 0) return [1]; + const numDigits = String(stone).length; + if (numDigits % 2 === 0) { + const half = numDigits / 2; + const left = parseInt(String(stone).slice(0, half)); + const right = parseInt(String(stone).slice(half)); + return [left, right]; + } + return [stone * 2024]; +}; + +const blinkStones = (stones) => { + let newStones = []; + for (const stone of stones) { + newStones.push(...transformStone(stone)); + } + return newStones; +}; + +const main = () => { + const input = fs.readFileSync(""input.txt"", ""utf8"").trim(); + let stones = input.split("" "").map(Number); + + for (let i = 0; i < 25; i++) { + stones = blinkStones(stones); + } + + console.log(stones.length); +}; + +main();",node:14 +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"const fs = require('fs'); + +// Function to read and parse the input from the file +const readStonesFromFile = (filePath) => { + return fs.readFileSync(filePath, 'utf-8') + .trim() + .split(/\s+/); +}; + +// Function to count the occurrences of each stone +const countStones = (stones) => { + return stones.reduce((counts, stone) => { + counts[stone] = (counts[stone] || 0n) + 1n; + return counts; + }, {}); +}; + +// Function to transform a single stone based on the given rules +const transformStone = (stone) => { + if (stone === '0') { + return ['1']; // '0' transforms to '1' + } + if (stone.length % 2 === 0) { + // If the stone length is even, split it into two parts + const mid = stone.length / 2; + const left = stone.slice(0, mid).replace(/^0+/, '') || '0'; + const right = stone.slice(mid).replace(/^0+/, '') || '0'; + return [left, right]; + } + // For odd length, multiply by 2024 + const num = BigInt(stone); + const newStone = (num * 2024n).toString(); + return [newStone]; +}; + +// Function to simulate the transformation for all stones +const transformAllStones = (stoneCounts) => { + let newStoneCounts = {}; + + Object.entries(stoneCounts).forEach(([stone, count]) => { + const transformedStones = transformStone(stone); + transformedStones.forEach(newStone => { + newStoneCounts[newStone] = (newStoneCounts[newStone] || 0n) + count; + }); + }); + + return newStoneCounts; +}; + +// Function to simulate multiple blinks by applying the transformation repeatedly +const simulateBlinks = (stoneCounts, numberOfBlinks) => { + let currentStoneCounts = stoneCounts; + for (let i = 0; i < numberOfBlinks; i++) { + currentStoneCounts = transformAllStones(currentStoneCounts); + } + return currentStoneCounts; +}; + +// Function to calculate the total number of stones +const getTotalStones = (stoneCounts) => { + return Object.values(stoneCounts).reduce((total, count) => total + count, 0n); +}; + +// Main function to read the input, simulate the process, and calculate the result +const main = () => { + const inputFilePath = 'input.txt'; + const numberOfBlinks = 75; + + // Step 1: Read and parse the stones from the file + const stones = readStonesFromFile(inputFilePath); + + // Step 2: Count the initial occurrences of each stone + const initialStoneCounts = countStones(stones); + + // Step 3: Simulate the blinking process for the given number of blinks + const finalStoneCounts = simulateBlinks(initialStoneCounts, numberOfBlinks); + + // Step 4: Calculate and output the total number of stones + const totalStones = getTotalStones(finalStoneCounts); + console.log(totalStones.toString()); +}; + +// Execute the main function +main();",node:14 +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"const fs = require('fs'); + +class PlutonianPebbleSimulation { + constructor(initialStones, blinks = 75) { + this.stones = initialStones; + this.blinks = blinks; + this.stoneCounts = this.initializeStoneCounts(); + } + + // Initialize the stone counts + initializeStoneCounts() { + return this.stones.reduce((counts, stone) => { + counts[stone] = (counts[stone] || 0n) + 1n; + return counts; + }, {}); + } + + // Process a single blink iteration + processBlink() { + const newStoneCounts = {}; + Object.entries(this.stoneCounts).forEach(([stone, count]) => { + const updatedStones = this.updateStone(stone, count); + updatedStones.forEach(newStone => { + newStoneCounts[newStone] = (newStoneCounts[newStone] || 0n) + count; + }); + }); + this.stoneCounts = newStoneCounts; + } + + // Determine the next stones based on the current one + updateStone(stone, count) { + if (stone === '0') { + return ['1']; + } else if (stone.length % 2 === 0) { + return this.splitStone(stone); + } else { + return [this.multiplyStone(stone)]; + } + } + + // Split an even-length stone into two parts + splitStone(stone) { + const half = stone.length / 2; + const left = stone.slice(0, half).replace(/^0+/, '') || '0'; + const right = stone.slice(half).replace(/^0+/, '') || '0'; + return [left, right]; + } + + // Multiply an odd-length stone by 2024 + multiplyStone(stone) { + const num = BigInt(stone); + return (num * 2024n).toString(); + } + + // Simulate the blinking process for a set number of times + simulate() { + for (let i = 0; i < this.blinks; i++) { + this.processBlink(); + } + return this.getTotalStones(); + } + + // Calculate the total number of stones + getTotalStones() { + return Object.values(this.stoneCounts).reduce((sum, count) => sum + count, 0n); + } +} + +// Read input and initialize simulation +function readInput(filename) { + const input = fs.readFileSync(filename, 'utf-8').trim(); + return input.split(/\s+/); +} + +// Main function to run the simulation +function main() { + const initialStones = readInput('input.txt'); + const simulation = new PlutonianPebbleSimulation(initialStones, 75); + const result = simulation.simulate(); + console.log(result.toString()); +} + +// Execute the solution +main();",node:14 +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"const fs = require('fs'); + +// Read and parse the input file +const readInput = (filePath) => { + return fs.readFileSync(filePath, 'utf-8') + .trim() + .split(/\s+/); +}; + +// Initialize stone counts using a Map +const initializeStoneCounts = (stones) => { + return stones.reduce((counts, stone) => { + counts.set(stone, (counts.get(stone) || 0n) + 1n); + return counts; + }, new Map()); +}; + +// Transform a single stone based on the rules +const transformStone = (stone) => { + if (stone === '0') { + return ['1']; + } else if (stone.length % 2 === 0) { + const half = stone.length / 2; + const left = stone.slice(0, half).replace(/^0+/, '') || '0'; + const right = stone.slice(half).replace(/^0+/, '') || '0'; + return [left, right]; + } else { + const num = BigInt(stone); + const newNum = num * 2024n; + return [newNum.toString()]; + } +}; + +// Simulate a single blink +const simulateBlink = (stoneCounts) => { + const newStoneCounts = new Map(); + for (const [stone, count] of stoneCounts.entries()) { + const transformedStones = transformStone(stone); + transformedStones.forEach(newStone => { + newStoneCounts.set(newStone, (newStoneCounts.get(newStone) || 0n) + count); + }); + } + return newStoneCounts; +}; + +// Simulate multiple blinks +const simulateBlinks = (stoneCounts, blinks) => { + let currentCounts = stoneCounts; + for (let i = 0; i < blinks; i++) { + currentCounts = simulateBlink(currentCounts); + } + return currentCounts; +}; + +// Calculate the total number of stones +const calculateTotalStones = (stoneCounts) => { + return Array.from(stoneCounts.values()).reduce((total, count) => total + count, 0n); +}; + +// Main function +const main = () => { + const filePath = 'input.txt'; + const blinks = 75; + + // Read and parse the input + const stones = readInput(filePath); + + // Initialize stone counts + const initialStoneCounts = initializeStoneCounts(stones); + + // Simulate blinks + const finalStoneCounts = simulateBlinks(initialStoneCounts, blinks); + + // Calculate and print the total number of stones + const totalStones = calculateTotalStones(finalStoneCounts); + console.log(totalStones.toString()); +}; + +// Run the program +main();",node:14 +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"const fs = require('fs'); + +// Function to read and parse the input file +function readInput(filePath) { + const data = fs.readFileSync(filePath, 'utf-8').trim(); + return data.split(/\s+/); +} + +// Function to initialize stone counts +function initializeStoneCounts(stones) { + const stoneCounts = {}; + for (const stone of stones) { + stoneCounts[stone] = (stoneCounts[stone] || 0n) + 1n; + } + return stoneCounts; +} + +// Function to transform a single stone +function transformStone(stone) { + if (stone === '0') { + return ['1']; + } else if (stone.length % 2 === 0) { + const half = stone.length / 2; + const left = stone.slice(0, half).replace(/^0+/, '') || '0'; + const right = stone.slice(half).replace(/^0+/, '') || '0'; + return [left, right]; + } else { + const num = BigInt(stone); + const newNum = num * 2024n; + return [newNum.toString()]; + } +} + +// Function to simulate blinks +function simulateBlinks(stoneCounts, blinks) { + for (let i = 0; i < blinks; i++) { + const newStoneCounts = {}; + for (const stone in stoneCounts) { + const count = stoneCounts[stone]; + const transformedStones = transformStone(stone); + for (const newStone of transformedStones) { + newStoneCounts[newStone] = (newStoneCounts[newStone] || 0n) + count; + } + } + stoneCounts = newStoneCounts; + } + return stoneCounts; +} + +// Function to calculate the total number of stones +function calculateTotalStones(stoneCounts) { + return Object.values(stoneCounts).reduce((total, count) => total + count, 0n); +} + +// Main function +function main() { + const filePath = 'input.txt'; + const blinks = 75; + + // Read and parse the input + const stones = readInput(filePath); + + // Initialize stone counts + let stoneCounts = initializeStoneCounts(stones); + + // Simulate blinks + stoneCounts = simulateBlinks(stoneCounts, blinks); + + // Calculate and print the total number of stones + const totalStones = calculateTotalStones(stoneCounts); + console.log(totalStones.toString()); +} + +// Run the program +main();",node:14 +2024,11,2,"--- Day 11: Plutonian Pebbles --- + +The ancient civilization on Pluto was known for its ability to manipulate spacetime, and while The Historians explore their infinite corridors, you've noticed a strange set of physics-defying stones. + +At first glance, they seem like normal stones: they're arranged in a perfectly straight line, and each stone has a number engraved on it. + +The strange part is that every time you blink, the stones change. + +Sometimes, the number engraved on a stone changes. Other times, a stone might split in two, causing all the other stones to shift over a bit to make room in their perfectly straight line. + +As you observe them for a while, you find that the stones have a consistent behavior. Every time you blink, the stones each simultaneously change according to the first applicable rule in this list: + +If the stone is engraved with the number 0, it is replaced by a stone engraved with the number 1. +If the stone is engraved with a number that has an even number of digits, it is replaced by two stones. The left half of the digits are engraved on the new left stone, and the right half of the digits are engraved on the new right stone. (The new numbers don't keep extra leading zeroes: 1000 would become stones 10 and 0.) +If none of the other rules apply, the stone is replaced by a new stone; the old stone's number multiplied by 2024 is engraved on the new stone. +No matter how the stones change, their order is preserved, and they stay on their perfectly straight line. + +How will the stones evolve if you keep blinking at them? You take a note of the number engraved on each stone in the line (your puzzle input). + +If you have an arrangement of five stones engraved with the numbers 0 1 10 99 999 and you blink once, the stones transform as follows: + +The first stone, 0, becomes a stone marked 1. +The second stone, 1, is multiplied by 2024 to become 2024. +The third stone, 10, is split into a stone marked 1 followed by a stone marked 0. +The fourth stone, 99, is split into two stones marked 9. +The fifth stone, 999, is replaced by a stone marked 2021976. +So, after blinking once, your five stones would become an arrangement of seven stones engraved with the numbers 1 2024 1 0 9 9 2021976. + +Here is a longer example: + +Initial arrangement: +125 17 + +After 1 blink: +253000 1 7 + +After 2 blinks: +253 0 2024 14168 + +After 3 blinks: +512072 1 20 24 28676032 + +After 4 blinks: +512 72 2024 2 0 2 4 2867 6032 + +After 5 blinks: +1036288 7 2 20 24 4048 1 4048 8096 28 67 60 32 + +After 6 blinks: +2097446912 14168 4048 2 0 2 4 40 48 2024 40 48 80 96 2 8 6 7 6 0 3 2 +In this example, after blinking six times, you would have 22 stones. After blinking 25 times, you would have 55312 stones! + +Consider the arrangement of stones in front of you. How many stones will you have after blinking 25 times? + +Your puzzle answer was 193607. + +--- Part Two --- + +The Historians sure are taking a long time. To be fair, the infinite corridors are very large. + +How many stones would you have after blinking a total of 75 times?",229557103025807,"const fs = require('fs'); + +let stones = fs.readFileSync('input.txt', 'utf-8').trim().split(/\s+/); + +const blinks = 75; + +let stoneCounts = {}; + +// Initialize the stone counts +for (let stone of stones) { + stoneCounts[stone] = (stoneCounts[stone] || 0n) + 1n; +} + +for (let i = 0; i < blinks; i++) { + let newStoneCounts = {}; + for (let stone in stoneCounts) { + let count = stoneCounts[stone]; + if (stone === '0') { + newStoneCounts['1'] = (newStoneCounts['1'] || 0n) + count; + } else if (stone.length % 2 === 0) { + let half = stone.length / 2; + let left = stone.slice(0, half).replace(/^0+/, '') || '0'; + let right = stone.slice(half).replace(/^0+/, '') || '0'; + newStoneCounts[left] = (newStoneCounts[left] || 0n) + count; + newStoneCounts[right] = (newStoneCounts[right] || 0n) + count; + } else { + let num = BigInt(stone); + let newNum = num * 2024n; + let newStone = newNum.toString(); + newStoneCounts[newStone] = (newStoneCounts[newStone] || 0n) + count; + } + } + stoneCounts = newStoneCounts; +} + +let totalStones = Object.values(stoneCounts).reduce((a, b) => a + b, 0n); + +console.log(totalStones.toString());",node:14 +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map?",1377008,"const fs = require('fs'); + +function main() { + const input = fs.readFileSync('input.txt', 'utf8'); + const lines = input.split('\n'); + + const grid = []; + for (let line of lines) { + if (line.startsWith('#') || !line.trim()) { + continue; + } + grid.push(line.trim().split('')); + } + + const rows = grid.length; + const cols = grid[0].length; + const visited = Array.from(Array(rows), () => Array(cols).fill(false)); + + let totalPrice = 0; + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (!visited[i][j]) { + const plantType = grid[i][j]; + let area = 0; + let perimeter = 0; + const queue = []; + queue.push([i, j]); + visited[i][j] = true; + + while (queue.length > 0) { + const [ci, cj] = queue.shift(); + area += 1; + + const directions = [[-1,0], [1,0], [0,-1], [0,1]]; + for (const [dx, dy] of directions) { + const ni = ci + dx; + const nj = cj + dy; + + if (ni < 0 || nj < 0 || ni >= rows || nj >= cols) { + perimeter += 1; + } else if (grid[ni][nj] !== plantType) { + perimeter += 1; + } else if (!visited[ni][nj]) { + queue.push([ni, nj]); + visited[ni][nj] = true; + } + } + } + + totalPrice += area * perimeter; + } + } + } + + console.log(totalPrice); +} + +main();",node:14 +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map?",1377008,"const fs = require('fs'); + +// Read and parse the input file +const readInput = filename => + fs.readFileSync(filename, 'utf8') + .split('\n') + .filter(line => line.trim() && !line.startsWith('#')) + .map(line => line.trim().split('')); + +// Calculate the area and perimeter of a region +const calculateAreaAndPerimeter = (grid, visited, i, j, plantType) => { + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; + const queue = [[i, j]]; + visited[i][j] = true; + + let area = 0; + let perimeter = 0; + + while (queue.length > 0) { + const [ci, cj] = queue.shift(); + area += 1; + + directions.forEach(([dx, dy]) => { + const ni = ci + dx; + const nj = cj + dy; + + if (ni < 0 || nj < 0 || ni >= grid.length || nj >= grid[0].length || grid[ni][nj] !== plantType) { + perimeter += 1; + } else if (!visited[ni][nj]) { + visited[ni][nj] = true; + queue.push([ni, nj]); + } + }); + } + + return { area, perimeter }; +}; + +// Explore the entire grid and calculate the total cost +const calculateTotalCost = grid => { + const rows = grid.length; + const cols = grid[0].length; + const visited = Array.from({ length: rows }, () => Array(cols).fill(false)); + + const getUnvisitedPlot = () => { + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (!visited[i][j]) { + return [i, j]; + } + } + } + return null; + }; + + const totalCost = [...Array(rows)].map(() => Array(cols).fill(0)).reduce((total, _, rowIndex) => { + return total + [...Array(cols)].reduce((rowTotal, _, colIndex) => { + if (!visited[rowIndex][colIndex]) { + const plantType = grid[rowIndex][colIndex]; + const { area, perimeter } = calculateAreaAndPerimeter(grid, visited, rowIndex, colIndex, plantType); + return rowTotal + area * perimeter; + } + return rowTotal; + }, 0); + }, 0); + + return totalCost; +}; + +// Main function to orchestrate the logic +const main = () => { + const grid = readInput('input.txt'); + const totalCost = calculateTotalCost(grid); + console.log(totalCost); +}; + +main();",node:14 +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map?",1377008,"const fs = require('fs'); + +// Read and parse the input file +function readInput(filename) { + return fs.readFileSync(filename, 'utf8') + .split('\n') + .filter(line => line.trim() && !line.startsWith('#')) + .map(line => line.trim().split('')); +} + +// Create a visited grid initialized to false +function createVisitedGrid(rows, cols) { + return Array.from({ length: rows }, () => Array(cols).fill(false)); +} + +// Perform breadth-first search to calculate area and perimeter +function exploreRegion(grid, visited, startRow, startCol, plantType) { + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; + const queue = [[startRow, startCol]]; + visited[startRow][startCol] = true; + + let area = 0; + let perimeter = 0; + + while (queue.length > 0) { + const [row, col] = queue.shift(); + area += 1; + + directions.forEach(([dx, dy]) => { + const newRow = row + dx; + const newCol = col + dy; + + if (newRow < 0 || newCol < 0 || newRow >= grid.length || newCol >= grid[0].length || grid[newRow][newCol] !== plantType) { + perimeter += 1; + } else if (!visited[newRow][newCol]) { + visited[newRow][newCol] = true; + queue.push([newRow, newCol]); + } + }); + } + + return { area, perimeter }; +} + +// Calculate the total cost by iterating over all unvisited plots +function calculateTotalCost(grid) { + const rows = grid.length; + const cols = grid[0].length; + const visited = createVisitedGrid(rows, cols); + let totalCost = 0; + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (!visited[i][j]) { + const plantType = grid[i][j]; + const { area, perimeter } = exploreRegion(grid, visited, i, j, plantType); + totalCost += area * perimeter; + } + } + } + + return totalCost; +} + +// Main function to execute the logic +function main() { + const grid = readInput('input.txt'); + const totalCost = calculateTotalCost(grid); + console.log(totalCost); +} + +main();",node:14 +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map?",1377008,"const fs = require('fs'); + +class PlantGrid { + constructor(filename) { + this.grid = this.readInput(filename); + this.rows = this.grid.length; + this.cols = this.grid[0].length; + this.visited = Array.from({ length: this.rows }, () => Array(this.cols).fill(false)); + this.totalCost = 0; + } + + // Read and parse the input file + readInput(filename) { + return fs.readFileSync(filename, 'utf8') + .split('\n') + .filter(line => line.trim() && !line.startsWith('#')) + .map(line => line.trim().split('')); + } + + // Explore a plot to calculate area and perimeter + explorePlot(i, j, plantType) { + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; + const queue = [[i, j]]; + this.visited[i][j] = true; + + let area = 0; + let perimeter = 0; + + while (queue.length > 0) { + const [ci, cj] = queue.shift(); + area += 1; + + directions.forEach(([dx, dy]) => { + const ni = ci + dx; + const nj = cj + dy; + + if (ni < 0 || nj < 0 || ni >= this.rows || nj >= this.cols || this.grid[ni][nj] !== plantType) { + perimeter += 1; + } else if (!this.visited[ni][nj]) { + this.visited[ni][nj] = true; + queue.push([ni, nj]); + } + }); + } + + return { area, perimeter }; + } + + // Calculate the total cost by exploring the grid + calculateTotalCost() { + for (let i = 0; i < this.rows; i++) { + for (let j = 0; j < this.cols; j++) { + if (!this.visited[i][j]) { + const plantType = this.grid[i][j]; + const { area, perimeter } = this.explorePlot(i, j, plantType); + this.totalCost += area * perimeter; + } + } + } + + return this.totalCost; + } +} + +// Main function to orchestrate the logic +function main() { + const plantGrid = new PlantGrid('input.txt'); + const totalCost = plantGrid.calculateTotalCost(); + console.log(totalCost); +} + +main();",node:14 +2024,12,1,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map?",1377008,"const fs = require('fs'); + +// Read input and parse into grid +function readInput(filename) { + const input = fs.readFileSync(filename, 'utf8'); + return input.split('\n').filter(line => line.trim() && !line.startsWith('#')) + .map(line => line.trim().split('')); +} + +// Explore a plot and calculate its area and perimeter +function explorePlot(grid, visited, i, j, plantType) { + const rows = grid.length; + const cols = grid[0].length; + let area = 0; + let perimeter = 0; + const queue = [[i, j]]; + visited[i][j] = true; + + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; + + while (queue.length > 0) { + const [ci, cj] = queue.shift(); + area += 1; + + for (const [dx, dy] of directions) { + const ni = ci + dx; + const nj = cj + dy; + + if (ni < 0 || nj < 0 || ni >= rows || nj >= cols || grid[ni][nj] !== plantType) { + perimeter += 1; + } else if (!visited[ni][nj]) { + visited[ni][nj] = true; + queue.push([ni, nj]); + } + } + } + + return { area, perimeter }; +} + +// Main function to calculate total price +function calculateTotalPrice(grid) { + const rows = grid.length; + const cols = grid[0].length; + const visited = Array.from(Array(rows), () => Array(cols).fill(false)); + let totalPrice = 0; + + for (let i = 0; i < rows; i++) { + for (let j = 0; j < cols; j++) { + if (!visited[i][j]) { + const plantType = grid[i][j]; + const { area, perimeter } = explorePlot(grid, visited, i, j, plantType); + totalPrice += area * perimeter; + } + } + } + + return totalPrice; +} + +// Main entry point +function main() { + const grid = readInput('input.txt'); + const totalPrice = calculateTotalPrice(grid); + console.log(totalPrice); +} + +main();",node:14 +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the Möbius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788,"// solution for https://adventofcode.com/2024/day/12 part 2 + +""use strict"" + +const input = Deno.readTextFileSync(""day12-input.txt"").trim() + +const garden = [ ] +const processed = [ ] + +var width = 0 +var height = 0 + +var currentSymbol = """" +var areaSize = 0 +var topBorderPlots = { } // by row +var bottomBorderPlots = { } // by row +var leftBorderPlots = { } // by col +var rightBorderPlots = { } // by col + +var result = 0 + + +function main() { + + processInput() + + for (let row = 0; row < height; row++) { + for (let col = 0; col < width; col++) { + + processPlot(row, col) + } + } + + console.log(""the answer is"", result) +} + +function processInput() { + + const lines = input.split(""\n"") + + for (const line of lines) { garden.push(line.trim()) } + + height = garden.length + width = garden[0].length + + for (const line of garden) { + + const doneLine = [ ] + processed.push(doneLine) + + for (const symbol of line) { doneLine.push(false) } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function processPlot(row, col) { + + if (processed[row][col]) { return } + + processed[row][col] = true + + currentSymbol = garden[row][col] + + areaSize = 0 + topBorderPlots = { } + bottomBorderPlots = { } + leftBorderPlots = { } + rightBorderPlots = { } + + walkFrom(row, col) + + result += areaSize * findNumberOfSides() +} + +function walkFrom(row, col) { + + const pointsToWalk = [ createPoint(row, col) ] + + while (true) { + + const point = pointsToWalk.pop() + + if (point == undefined) { return } + + areaSize += 1 + + const row = point.row + const col = point.col + + tryCatchNeighbor(row, col, -1, 0, pointsToWalk) + tryCatchNeighbor(row, col, +1, 0, pointsToWalk) + tryCatchNeighbor(row, col, 0, -1, pointsToWalk) + tryCatchNeighbor(row, col, 0, +1, pointsToWalk) + } +} + +function tryCatchNeighbor(baseRow, baseCol, deltaRow, deltaCol, pointsToWalk) { + + const neighborRow = baseRow + deltaRow + const neighborCol = baseCol + deltaCol + + if (neighborRow < 0) { pushToTopBorderPlots(baseRow, baseCol); return } + if (neighborCol < 0) { pushToLeftBorderPlots(baseRow, baseCol); return } + + if (neighborRow == height) { pushToBottomBorderPlots(baseRow, baseCol); return } + if (neighborCol == width) { pushToRightBorderPlots(baseRow, baseCol); return } + + if (garden[neighborRow][neighborCol] != currentSymbol) { + + if (neighborRow < baseRow) { pushToTopBorderPlots(baseRow, baseCol); return } + if (neighborCol < baseCol) { pushToLeftBorderPlots(baseRow, baseCol); return } + + if (neighborRow > baseRow) { pushToBottomBorderPlots(baseRow, baseCol); return } + if (neighborCol > baseCol) { pushToRightBorderPlots(baseRow, baseCol); return } + } + + if (processed[neighborRow][neighborCol]) { return } + + processed[neighborRow][neighborCol] = true + + pointsToWalk.push(createPoint(neighborRow, neighborCol)) +} + +function createPoint(row, col) { + + return { ""row"": row, ""col"": col } +} + +function pushToTopBorderPlots(row, col) { + + if (topBorderPlots[row] == undefined) { topBorderPlots[row] = [ ] } + + topBorderPlots[row].push(col) +} + +function pushToBottomBorderPlots(row, col) { + + if (bottomBorderPlots[row] == undefined) { bottomBorderPlots[row] = [ ] } + + bottomBorderPlots[row].push(col) +} + +function pushToLeftBorderPlots(row, col) { + + if (leftBorderPlots[col] == undefined) { leftBorderPlots[col] = [ ] } + + leftBorderPlots[col].push(row) +} + +function pushToRightBorderPlots(row, col) { + + if (rightBorderPlots[col] == undefined) { rightBorderPlots[col] = [ ] } + + rightBorderPlots[col].push(row) +} + +/////////////////////////////////////////////////////////////////////////////// + +function findNumberOfSides() { + + let sides = 0 + + for (const dict of [ topBorderPlots, bottomBorderPlots, leftBorderPlots, rightBorderPlots ]) { + + sides += findNumberOfSidesThis(dict) + } + return sides +} + +function findNumberOfSidesThis(dict) { + + let sides = 0 + + for (const list of Object.values(dict)) { + + sides += findNumberOfSidesThisList(list) + } + return sides +} + +function findNumberOfSidesThisList(list) { + + list.sort(function (a, b) { return a - b }) + + const newList = [ ] + + while (true) { + + const candidate = list.shift() + if (candidate == undefined) { break } + + const previous = newList.at(-1) + + if (previous == undefined) { newList.push(candidate); continue } + + if (candidate - previous == 1) { newList.pop() } // removing neighbor on same same side + + newList.push(candidate) + } + + return newList.length +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 17ms",node:14 +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the Möbius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788,"const fs = require('fs'); + +// Read and prepare the input data +const data = fs.readFileSync('input.txt', 'utf-8').split('\n'); +const xmax = data[0].length; +const ymax = data.length; +const totalSeen = new Set(); + +// Helper function to count corners around a given plant at coordinates (x, y) +const countCorners = (plant, x, y) => { + const up = y > 0 ? data[y - 1][x] : null; + const down = y < ymax - 1 ? data[y + 1][x] : null; + const left = x > 0 ? data[y][x - 1] : null; + const right = x < xmax - 1 ? data[y][x + 1] : null; + + let corners = 0; + const count = [up, down, left, right].filter(i => i === plant).length; + + if (count === 0) return 4; + if (count === 1) return 2; + if (count === 2) { + if ((left === right && left === plant) || (up === down && up === plant)) return 0; + corners += 1; + } + + // Check for corner conditions + if (up === left && up === plant && y > 0 && x > 0 && data[y - 1][x - 1] !== plant) corners += 1; + if (up === right && up === plant && y > 0 && x < xmax - 1 && data[y - 1][x + 1] !== plant) corners += 1; + if (down === left && down === plant && y < ymax - 1 && x > 0 && data[y + 1][x - 1] !== plant) corners += 1; + if (down === right && down === plant && y < ymax - 1 && x < xmax - 1 && data[y + 1][x + 1] !== plant) corners += 1; + + return corners; +}; + +// Function to calculate the area and perimeter of a plot at coordinates (x, y) +const calcPlot = (x, y) => { + const plant = data[y][x]; + let perimeter = 0; + let area = 0; + let corners = 0; + const seen = new Set(); + const queue = [[x, y]]; + + while (queue.length > 0) { + const [xi, yi] = queue.shift(); + + if (seen.has(`${xi},${yi}`)) continue; + + if (xi < 0 || xi >= xmax || yi < 0 || yi >= ymax || data[yi][xi] !== plant) { + perimeter += 1; + continue; + } + + seen.add(`${xi},${yi}`); + area += 1; + corners += countCorners(plant, xi, yi); + + // Add neighboring coordinates to the queue + queue.push([xi + 1, yi]); + queue.push([xi - 1, yi]); + queue.push([xi, yi + 1]); + queue.push([xi, yi - 1]); + } + + // Update the global totalSeen set + seen.forEach(loc => totalSeen.add(loc)); + + return area * corners; +}; + +// Main loop to calculate the total cost +let totalCost = 0; +for (let yi = 0; yi < ymax; yi++) { + for (let xi = 0; xi < xmax; xi++) { + if (totalSeen.has(`${xi},${yi}`)) continue; + totalCost += calcPlot(xi, yi); + } +} + +console.log(totalCost);",node:14 +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the Möbius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788,"const fs = require('fs'); + +// Read the input file and split it into lines +const grid = fs.readFileSync('input.txt', 'utf-8').split('\n').map(line => line.split('')); + +function addToRegionFrom(grid, loc, region, visited) { + region.add(loc.toString()); + visited.add(loc.toString()); + + const neighbors = [ + [loc[0] - 1, loc[1]], + [loc[0] + 1, loc[1]], + [loc[0], loc[1] - 1], + [loc[0], loc[1] + 1] + ]; + + const validNeighbors = neighbors.filter(pt => pt[0] >= 0 && pt[0] < grid.length && pt[1] >= 0 && pt[1] < grid[0].length); + + for (const neighbor of validNeighbors) { + if (grid[loc[0]][loc[1]] === grid[neighbor[0]][neighbor[1]] && !visited.has(neighbor.toString())) { + addToRegionFrom(grid, neighbor, region, visited); + } + } +} + +function getArea(region) { + return region.size; +} + +function getSides(region) { + let sides = 0; + const visitedEdges = new Set(); + + const sortedRegion = Array.from(region).sort(); + + for (const locStr of sortedRegion) { + const loc = locStr.split(',').map(Number); + + const above = [loc[0] - 1, loc[1]]; + if (!region.has(above.toString())) { + visitedEdges.add(above.toString() + '-bottom'); + if (!visitedEdges.has([above[0], above[1] - 1].toString() + '-bottom') && !visitedEdges.has([above[0], above[1] + 1].toString() + '-bottom')) { + sides++; + } + } + + const below = [loc[0] + 1, loc[1]]; + if (!region.has(below.toString())) { + visitedEdges.add(below.toString() + '-top'); + if (!visitedEdges.has([below[0], below[1] - 1].toString() + '-top') && !visitedEdges.has([below[0], below[1] + 1].toString() + '-top')) { + sides++; + } + } + + const left = [loc[0], loc[1] - 1]; + if (!region.has(left.toString())) { + visitedEdges.add(left.toString() + '-right'); + if (!visitedEdges.has([left[0] - 1, left[1]].toString() + '-right') && !visitedEdges.has([left[0] + 1, left[1]].toString() + '-right')) { + sides++; + } + } + + const right = [loc[0], loc[1] + 1]; + if (!region.has(right.toString())) { + visitedEdges.add(right.toString() + '-left'); + if (!visitedEdges.has([right[0] - 1, right[1]].toString() + '-left') && !visitedEdges.has([right[0] + 1, right[1]].toString() + '-left')) { + sides++; + } + } + } + + return sides; +} + +function getCorners(region) { + let corners = 0; + + for (const locStr of region) { + const loc = locStr.split(',').map(Number); + + const outerTopLeft = [[0, -1, false], [-1, 0, false]]; + const outerTopRight = [[0, 1, false], [-1, 0, false]]; + const outerBottomRight = [[0, 1, false], [1, 0, false]]; + const outerBottomLeft = [[0, -1, false], [1, 0, false]]; + + const innerTopLeft = [[0, 1, true], [1, 0, true], [1, 1, false]]; + const innerTopRight = [[0, -1, true], [1, 0, true], [1, -1, false]]; + const innerBottomRight = [[0, -1, true], [-1, 0, true], [-1, -1, false]]; + const innerBottomLeft = [[0, 1, true], [-1, 0, true], [-1, 1, false]]; + + const allNeighbors = [ + outerTopLeft, outerTopRight, outerBottomRight, outerBottomLeft, + innerTopLeft, innerTopRight, innerBottomRight, innerBottomLeft + ]; + + corners += allNeighbors.reduce((acc, neighbor) => { + return acc + (neighbor.every(([dx, dy, isInner]) => { + const neighborLoc = [loc[0] + dx, loc[1] + dy]; + return (region.has(neighborLoc.toString()) === isInner); + }) ? 1 : 0); + }, 0); + } + + return corners; +} + +function getPerimeter(region) { + let perimeter = 0; + + for (const locStr of region) { + const loc = locStr.split(',').map(Number); + const neighbors = [ + [loc[0] - 1, loc[1]], + [loc[0] + 1, loc[1]], + [loc[0], loc[1] - 1], + [loc[0], loc[1] + 1] + ]; + perimeter += neighbors.filter(pt => !region.has(pt.toString())).length; + } + + return perimeter; +} + +// Main logic +let visited = new Set(); +let regions = []; + +for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + if (!visited.has([i, j].toString())) { + let region = new Set(); + addToRegionFrom(grid, [i, j], region, visited); + regions.push(region); + } + visited.add([i, j].toString()); + } +} + +let totalPrice = 0; + +for (const region of regions) { + const price = getArea(region) * getCorners(region); + totalPrice += price; +} + +console.log(totalPrice);",node:14 +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the Möbius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788,"const fs = require('fs'); + +// Read the input file and split it into lines +const data = fs.readFileSync('input.txt', 'utf-8').split('\n'); + +const xmax = data[0].length; +const ymax = data.length; + +const totalSeen = new Set(); + +function countCorners(plant, x, y) { + const up = y - 1 >= 0 ? data[y - 1][x] : null; + const down = y + 1 < ymax ? data[y + 1][x] : null; + const left = x - 1 >= 0 ? data[y][x - 1] : null; + const right = x + 1 < xmax ? data[y][x + 1] : null; + + let count = [up, down, left, right].filter(i => i === plant).length; + let corners = 0; + + if (count === 0) return 4; + if (count === 1) return 2; + if (count === 2) { + if ((left === right && left === plant) || (up === down && up === plant)) return 0; + corners += 1; + } + + if (up === left && up === plant && y - 1 >= 0 && x - 1 >= 0 && data[y - 1][x - 1] !== plant) corners += 1; + if (up === right && up === plant && y - 1 >= 0 && x + 1 < xmax && data[y - 1][x + 1] !== plant) corners += 1; + if (down === left && down === plant && y + 1 < ymax && x - 1 >= 0 && data[y + 1][x - 1] !== plant) corners += 1; + if (down === right && down === plant && y + 1 < ymax && x + 1 < xmax && data[y + 1][x + 1] !== plant) corners += 1; + + return corners; +} + +function calcPlot(x, y) { + const plant = data[y][x]; + + let perimeter = 0; + let area = 0; + let corners = 0; + const seen = new Set(); + + const q = []; + q.push([x, y]); + + while (q.length > 0) { + const [xi, yi] = q.shift(); + + if (seen.has(`${xi},${yi}`)) continue; + + if (xi < 0 || xi >= xmax || yi < 0 || yi >= ymax || data[yi][xi] !== plant) { + perimeter += 1; + continue; + } + + seen.add(`${xi},${yi}`); + area += 1; + corners += countCorners(plant, xi, yi); + + q.push([xi + 1, yi]); + q.push([xi - 1, yi]); + q.push([xi, yi + 1]); + q.push([xi, yi - 1]); + } + + // Add the seen cells to the totalSeen set + seen.forEach(loc => totalSeen.add(loc)); + + return area * corners; +} + +let total = 0; +for (let yi = 0; yi < ymax; yi++) { + for (let xi = 0; xi < xmax; xi++) { + if (totalSeen.has(`${xi},${yi}`)) continue; + + total += calcPlot(xi, yi); + } +} + +console.log(total);",node:14 +2024,12,2,"--- Day 12: Garden Groups --- + +Why not search for the Chief Historian near the gardener and his massive farm? There's plenty of food, so The Historians grab something to eat while they search. + +You're about to settle near a complex arrangement of garden plots when some Elves ask if you can lend a hand. They'd like to set up fences around each region of garden plots, but they can't figure out how much fence they need to order or how much it will cost. They hand you a map (your puzzle input) of the garden plots. + +Each garden plot grows only a single type of plant and is indicated by a single letter on your map. When multiple garden plots are growing the same type of plant and are touching (horizontally or vertically), they form a region. For example: + +AAAA +BBCD +BBCC +EEEC +This 4x4 arrangement includes garden plots growing five different types of plants (labeled A, B, C, D, and E), each grouped into their own region. + +In order to accurately calculate the cost of the fence around a single region, you need to know that region's area and perimeter. + +The area of a region is simply the number of garden plots the region contains. The above map's type A, B, and C plants are each in a region of area 4. The type E plants are in a region of area 3; the type D plants are in a region of area 1. + +Each garden plot is a square and so has four sides. The perimeter of a region is the number of sides of garden plots in the region that do not touch another garden plot in the same region. The type A and C plants are each in a region with perimeter 10. The type B and E plants are each in a region with perimeter 8. The lone D plot forms its own region with perimeter 4. + +Visually indicating the sides of plots in each region that contribute to the perimeter using - and |, the above map's regions' perimeters are measured as follows: + ++-+-+-+-+ +|A A A A| ++-+-+-+-+ +-+ + |D| ++-+-+ +-+ +-+ +|B B| |C| ++ + + +-+ +|B B| |C C| ++-+-+ +-+ + + |C| ++-+-+-+ +-+ +|E E E| ++-+-+-+ +Plants of the same type can appear in multiple separate regions, and regions can even appear within other regions. For example: + +OOOOO +OXOXO +OOOOO +OXOXO +OOOOO +The above map contains five regions, one containing all of the O garden plots, and the other four each containing a single X plot. + +The four X regions each have area 1 and perimeter 4. The region containing 21 type O plants is more complicated; in addition to its outer edge contributing a perimeter of 20, its boundary with each X region contributes an additional 4 to its perimeter, for a total perimeter of 36. + +Due to ""modern"" business practices, the price of fence required for a region is found by multiplying that region's area by its perimeter. The total price of fencing all regions on a map is found by adding together the price of fence for every region on the map. + +In the first example, region A has price 4 * 10 = 40, region B has price 4 * 8 = 32, region C has price 4 * 10 = 40, region D has price 1 * 4 = 4, and region E has price 3 * 8 = 24. So, the total price for the first example is 140. + +In the second example, the region with all of the O plants has price 21 * 36 = 756, and each of the four smaller X regions has price 1 * 4 = 4, for a total price of 772 (756 + 4 + 4 + 4 + 4). + +Here's a larger example: + +RRRRIICCFF +RRRRIICCCF +VVRRRCCFFF +VVRCCCJFFF +VVVVCJJCFE +VVIVCCJJEE +VVIIICJJEE +MIIIIIJJEE +MIIISIJEEE +MMMISSJEEE +It contains: + +A region of R plants with price 12 * 18 = 216. +A region of I plants with price 4 * 8 = 32. +A region of C plants with price 14 * 28 = 392. +A region of F plants with price 10 * 18 = 180. +A region of V plants with price 13 * 20 = 260. +A region of J plants with price 11 * 20 = 220. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 18 = 234. +A region of I plants with price 14 * 22 = 308. +A region of M plants with price 5 * 12 = 60. +A region of S plants with price 3 * 8 = 24. +So, it has a total price of 1930. + +What is the total price of fencing all regions on your map? + +Your puzzle answer was 1377008. + +--- Part Two --- + +Fortunately, the Elves are trying to order so much fence that they qualify for a bulk discount! + +Under the bulk discount, instead of using the perimeter to calculate the price, you need to use the number of sides each region has. Each straight section of fence counts as a side, regardless of how long it is. + +Consider this example again: + +AAAA +BBCD +BBCC +EEEC +The region containing type A plants has 4 sides, as does each of the regions containing plants of type B, D, and E. However, the more complex region containing the plants of type C has 8 sides! + +Using the new method of calculating the per-region price by multiplying the region's area by its number of sides, regions A through E have prices 16, 16, 32, 4, and 12, respectively, for a total price of 80. + +The second example above (full of type X and O plants) would have a total price of 436. + +Here's a map that includes an E-shaped region full of type E plants: + +EEEEE +EXXXX +EEEEE +EXXXX +EEEEE +The E-shaped region has an area of 17 and 12 sides for a price of 204. Including the two regions full of type X plants, this map has a total price of 236. + +This map has a total price of 368: + +AAAAAA +AAABBA +AAABBA +ABBAAA +ABBAAA +AAAAAA +It includes two regions full of type B plants (each with 4 sides) and a single region full of type A plants (with 4 sides on the outside and 8 more sides on the inside, a total of 12 sides). Be especially careful when counting the fence around regions like the one full of type A plants; in particular, each section of fence has an in-side and an out-side, so the fence does not connect across the middle of the region (where the two B regions touch diagonally). (The Elves would have used the Möbius Fencing Company instead, but their contract terms were too one-sided.) + +The larger example from before now has the following updated prices: + +A region of R plants with price 12 * 10 = 120. +A region of I plants with price 4 * 4 = 16. +A region of C plants with price 14 * 22 = 308. +A region of F plants with price 10 * 12 = 120. +A region of V plants with price 13 * 10 = 130. +A region of J plants with price 11 * 12 = 132. +A region of C plants with price 1 * 4 = 4. +A region of E plants with price 13 * 8 = 104. +A region of I plants with price 14 * 16 = 224. +A region of M plants with price 5 * 6 = 30. +A region of S plants with price 3 * 6 = 18. +Adding these together produces its new total price of 1206. + +What is the new total price of fencing all regions on your map?",815788,"const fs = require('fs'); + +// Read the input file and split it into lines +const data = fs.readFileSync('input.txt', 'utf-8').split('\n'); + +const xmax = data[0].length; +const ymax = data.length; + +const totalSeen = new Set(); + +function countCorners(plant, x, y) { + const up = y - 1 >= 0 ? data[y - 1][x] : null; + const down = y + 1 < ymax ? data[y + 1][x] : null; + const left = x - 1 >= 0 ? data[y][x - 1] : null; + const right = x + 1 < xmax ? data[y][x + 1] : null; + + let count = [up, down, left, right].filter(i => i === plant).length; + let corners = 0; + + if (count === 0) return 4; + if (count === 1) return 2; + if (count === 2) { + if ((left === right && left === plant) || (up === down && up === plant)) return 0; + corners += 1; + } + + if (up === left && up === plant && y - 1 >= 0 && x - 1 >= 0 && data[y - 1][x - 1] !== plant) corners += 1; + if (up === right && up === plant && y - 1 >= 0 && x + 1 < xmax && data[y - 1][x + 1] !== plant) corners += 1; + if (down === left && down === plant && y + 1 < ymax && x - 1 >= 0 && data[y + 1][x - 1] !== plant) corners += 1; + if (down === right && down === plant && y + 1 < ymax && x + 1 < xmax && data[y + 1][x + 1] !== plant) corners += 1; + + return corners; +} + +function calcPlot(x, y) { + const plant = data[y][x]; + + let perimeter = 0; + let area = 0; + let corners = 0; + const seen = new Set(); + + const q = []; + q.push([x, y]); + + while (q.length > 0) { + const [xi, yi] = q.shift(); + + if (seen.has(`${xi},${yi}`)) continue; + + if (xi < 0 || xi >= xmax || yi < 0 || yi >= ymax || data[yi][xi] !== plant) { + perimeter += 1; + continue; + } + + seen.add(`${xi},${yi}`); + area += 1; + corners += countCorners(plant, xi, yi); + + q.push([xi + 1, yi]); + q.push([xi - 1, yi]); + q.push([xi, yi + 1]); + q.push([xi, yi - 1]); + } + + seen.forEach(loc => totalSeen.add(loc)); + + return area * corners; +} + +let total = 0; +for (let yi = 0; yi < ymax; yi++) { + for (let xi = 0; xi < xmax; xi++) { + if (totalSeen.has(`${xi},${yi}`)) continue; + + total += calcPlot(xi, yi); + } +} + +console.log(total);",node:14 +2024,13,1,"--- 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?",34787,"const fs = require('fs'); + +const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n\n'); + +let totalTokens = 0; + +input.forEach(machine => { + const lines = machine.split('\n'); + const aButton = lines[0].match(/-?\d+/g).map(Number); + const bButton = lines[1].match(/-?\d+/g).map(Number); + const prize = lines[2].match(/-?\d+/g).map(Number); + + let minTokens = Infinity; + + for (let a = 0; a <= 100; a++) { + for (let b = 0; b <= 100; b++) { + const x = a * aButton[0] + b * bButton[0]; + const y = a * aButton[1] + b * bButton[1]; + if (x === prize[0] && y === prize[1]) { + const tokens = a * 3 + b * 1; + if (tokens < minTokens) { + minTokens = tokens; + } + } + } + } + + if (minTokens !== Infinity) { + totalTokens += minTokens; + } +}); + +console.log(totalTokens);",node:14 +2024,13,1,"--- 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?",34787,"const fs = require('fs'); + +function parseInput(data) { + const machines = []; + const lines = data.split('\n').filter(line => line.trim() !== ''); + for (let i = 0; i < lines.length; i += 3) { + const buttonA = lines[i].match(/Button A: X\+(\d+), Y\+(\d+)/); + const buttonB = lines[i+1].match(/Button B: X\+(\d+), Y\+(\d+)/); + const prize = lines[i+2].match(/Prize: X=(\d+), Y=(\d+)/); + if (buttonA && buttonB && prize) { + machines.push({ + A: {x: parseInt(buttonA[1]), y: parseInt(buttonA[2]), cost: 3}, + B: {x: parseInt(buttonB[1]), y: parseInt(buttonB[2]), cost: 1}, + prize: {x: parseInt(prize[1]), y: parseInt(prize[2])} + }); + } + } + return machines; +} + +function findMinCost(machine) { + let minCost = Infinity; + for (let a = 0; a <= 100; a++) { + for (let b = 0; b <= 100; b++) { + if ( + machine.A.x * a + machine.B.x * b === machine.prize.x && + machine.A.y * a + machine.B.y * b === machine.prize.y + ) { + const cost = machine.A.cost * a + machine.B.cost * b; + if (cost < minCost) { + minCost = cost; + } + } + } + } + return minCost; +} + +function calculateTotalMinTokens(filePath) { + const data = fs.readFileSync(filePath, 'utf-8'); + const machines = parseInput(data); + let totalTokens = 0; + machines.forEach(machine => { + const cost = findMinCost(machine); + if (cost !== Infinity) { + totalTokens += cost; + } + }); + return totalTokens; +} + +const total = calculateTotalMinTokens('input.txt'); +console.log(`Minimum total tokens required: ${total}`);",node:14 +2024,13,1,"--- 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?",34787,"const fs = require('fs'); + +// Parse input data and return machine configurations +const parseMachineData = (data) => { + return data.split('\n') + .filter(line => line.trim() !== '') + .reduce((machines, line, index, lines) => { + if (index % 3 === 0) { + const buttonA = lines[index].match(/Button A: X\+(\d+), Y\+(\d+)/); + const buttonB = lines[index + 1].match(/Button B: X\+(\d+), Y\+(\d+)/); + const prize = lines[index + 2].match(/Prize: X=(\d+), Y=(\d+)/); + + if (buttonA && buttonB && prize) { + machines.push({ + A: { x: parseInt(buttonA[1]), y: parseInt(buttonA[2]), cost: 3 }, + B: { x: parseInt(buttonB[1]), y: parseInt(buttonB[2]), cost: 1 }, + prize: { x: parseInt(prize[1]), y: parseInt(prize[2]) }, + }); + } + } + return machines; + }, []); +}; + +// Calculate the minimum cost to win the prize for a given machine +const calculateMinCostForMachine = ({ A, B, prize }) => { + let minCost = Infinity; + + for (let a = 0; a <= 100; a++) { + for (let b = 0; b <= 100; b++) { + const xPos = A.x * a + B.x * b; + const yPos = A.y * a + B.y * b; + + if (xPos === prize.x && yPos === prize.y) { + const cost = A.cost * a + B.cost * b; + minCost = Math.min(minCost, cost); + } + } + } + + return minCost === Infinity ? null : minCost; +}; + +// Main function to read the input and calculate the total minimum tokens +const calculateTotalTokens = (filePath) => { + const data = fs.readFileSync(filePath, 'utf-8'); + const machines = parseMachineData(data); + + return machines.reduce((totalTokens, machine) => { + const cost = calculateMinCostForMachine(machine); + return cost ? totalTokens + cost : totalTokens; + }, 0); +}; + +const totalTokens = calculateTotalTokens('input.txt'); +console.log(`Total minimum tokens required: ${totalTokens}`);",node:14 +2024,13,1,"--- 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?",34787,"const fs = require('fs'); + +class ClawMachine { + constructor(aButton, bButton, prize) { + this.aButton = aButton; + this.bButton = bButton; + this.prize = prize; + } + + findMinimumTokens() { + let minTokens = Infinity; + for (let a = 0; a <= 100; a++) { + for (let b = 0; b <= 100; b++) { + const x = a * this.aButton[0] + b * this.bButton[0]; + const y = a * this.aButton[1] + b * this.bButton[1]; + if (x === this.prize[0] && y === this.prize[1]) { + const tokens = a * 3 + b * 1; + minTokens = Math.min(minTokens, tokens); + } + } + } + return minTokens !== Infinity ? minTokens : 0; + } +} + +function parseInput(data) { + return data.split('\n\n').map(machine => { + const [aButton, bButton, prize] = machine.split('\n').map(line => + line.match(/-?\d+/g).map(Number) + ); + return new ClawMachine(aButton, bButton, prize); + }); +} + +function main() { + const data = fs.readFileSync('input.txt', 'utf8').trim(); + const machines = parseInput(data); + const totalTokens = machines.reduce((sum, machine) => sum + machine.findMinimumTokens(), 0); + console.log(totalTokens); +} + +main();",node:14 +2024,13,1,"--- 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?",34787,"const fs = require('fs'); + +function calculateMinimumTokens(machines) { + return machines.reduce((totalTokens, machine) => { + const [aButton, bButton, prize] = machine.split('\n').map(line => + line.match(/-?\d+/g).map(Number) + ); + let minTokens = Infinity; + + for (let aPresses = 0; aPresses <= 100; aPresses++) { + for (let bPresses = 0; bPresses <= 100; bPresses++) { + const xPosition = aPresses * aButton[0] + bPresses * bButton[0]; + const yPosition = aPresses * aButton[1] + bPresses * bButton[1]; + if (xPosition === prize[0] && yPosition === prize[1]) { + const tokensSpent = aPresses * 3 + bPresses * 1; + minTokens = Math.min(minTokens, tokensSpent); + } + } + } + + return totalTokens + (minTokens !== Infinity ? minTokens : 0); + }, 0); +} + +const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n\n'); +const result = calculateMinimumTokens(input); +console.log(result);",node:14 +2024,13,2,"--- 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 34787. + +--- 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?",85644161121698,"const fs = require('fs'); + +function parseInput(data) { + const machines = []; + const lines = data.split('\n').filter(line => line.trim() !== ''); + for (let i = 0; i < lines.length; i += 3) { + const buttonA = lines[i].match(/Button A: X\+(\d+), Y\+(\d+)/); + const buttonB = lines[i+1].match(/Button B: X\+(\d+), Y\+(\d+)/); + const prize = lines[i+2].match(/Prize: X=(\d+), Y=(\d+)/); + if (buttonA && buttonB && prize) { + machines.push({ + A: {x: parseInt(buttonA[1]), y: parseInt(buttonA[2]), cost: 3}, + B: {x: parseInt(buttonB[1]), y: parseInt(buttonB[2]), cost: 1}, + prize: {x: parseInt(prize[1]) + 10000000000000, y: parseInt(prize[2]) + 10000000000000} + }); + } + } + return machines; +} + +function findMinCost(machine) { + const { A, B, prize } = machine; + const Xp = prize.x; + const Yp = prize.y; + + const det = A.x * B.y - A.y * B.x; + if (det === 0) { + return Infinity; + } + + // Calculate determinants for Cramer's rule + const detA = Xp * B.y - Yp * B.x; + const detB = A.x * Yp - A.y * Xp; + + if (det === 0) return Infinity; + + const a = detA / det; + const b = detB / det; + + if (!Number.isInteger(a) || !Number.isInteger(b) || a < 0 || b < 0) { + return Infinity; + } + + return A.cost * a + B.cost * b; +} + +function calculateTotalMinTokens(filePath) { + const data = fs.readFileSync(filePath, 'utf-8'); + const machines = parseInput(data); + let totalTokens = 0; + machines.forEach(machine => { + const cost = findMinCost(machine); + if (cost !== Infinity) { + totalTokens += cost; + } + }); + return totalTokens; +} + +const total = calculateTotalMinTokens('input.txt'); +console.log(`Minimum total tokens required: ${total}`);",node:14 +2024,13,2,"--- 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 34787. + +--- 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?",85644161121698,"const fs = require('fs'); + +function solveClawMachines(input, partTwo = false) { + const machines = input.split('\n\n').map(machine => { + const [aButton, bButton, prize] = machine.split('\n').map(line => + line.match(/-?\d+/g).map(Number) + ); + return { aButton, bButton, prize }; + }); + + let totalTokens = 0; + + machines.forEach(({ aButton, bButton, prize }) => { + if (partTwo) { + prize[0] += 10000000000000; + prize[1] += 10000000000000; + } + + let minTokens = Infinity; + + // Use a mathematical approach to solve the system of equations: + // a * aButton[0] + b * bButton[0] = prize[0] + // a * aButton[1] + b * bButton[1] = prize[1] + const determinant = aButton[0] * bButton[1] - aButton[1] * bButton[0]; + + if (determinant !== 0) { + const a = (prize[0] * bButton[1] - prize[1] * bButton[0]) / determinant; + const b = (aButton[0] * prize[1] - aButton[1] * prize[0]) / determinant; + + if (Number.isInteger(a) && Number.isInteger(b) && a >= 0 && b >= 0) { + const tokens = a * 3 + b * 1; + minTokens = Math.min(minTokens, tokens); + } + } + + if (minTokens !== Infinity) { + totalTokens += minTokens; + } + }); + + return totalTokens; +} + +const input = fs.readFileSync('input.txt', 'utf8').trim(); + +// Part One +console.log(""Part One:"", solveClawMachines(input)); + +// Part Two +console.log(""Part Two:"", solveClawMachines(input, true));",node:14 +2024,13,2,"--- 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 34787. + +--- 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?",85644161121698,"const fs = require('fs'); +const { log } = require('console'); + +// Read and parse the input file +const readAndParseInput = (filePath) => { + return fs.readFileSync(filePath, 'utf-8') + .split('\n\n') + .map(machine => machine + .split('\n') + .map(line => line + .split(': ') + .slice(1) + .map(p => p.split(', ')) + ) + ); +}; + +// Brute-force function to find the minimum cost +const bruteForce = (ax, ay, bx, by, pricex, pricey) => { + let minCosts = Infinity; + for (let i = 0; i <= 100; i++) { + for (let j = 0; j <= 100; j++) { + if (ax * i + bx * j === pricex && ay * i + by * j === pricey) { + const costs = i * 3 + j; + minCosts = Math.min(minCosts, costs); + } + } + } + return minCosts; +}; + +// Extract machine parameters from raw data +const extractMachineParams = (machine) => { + const [aRaw, bRaw, prizeRaw] = machine.flat(); + return { + ax: parseInt(aRaw[0].split('+')[1]), + ay: parseInt(aRaw[1].split('+')[1]), + bx: parseInt(bRaw[0].split('+')[1]), + by: parseInt(bRaw[1].split('+')[1]), + prizex: parseInt(prizeRaw[0].split('=')[1]), + prizey: parseInt(prizeRaw[1].split('=')[1]), + }; +}; + +// Calculate part 1 solution +const calculatePart1 = (machines) => { + let totalCost = 0; + machines.forEach(machine => { + const { ax, ay, bx, by, prizex, prizey } = extractMachineParams(machine); + const cost = bruteForce(ax, ay, bx, by, prizex, prizey); + if (cost !== Infinity) { + totalCost += cost; + } + }); + return totalCost; +}; + +// Calculate part 2 solution +const calculatePart2 = (machines) => { + let totalCost = 0; + machines.forEach(machine => { + const { ax, ay, bx, by, prizex, prizey } = extractMachineParams(machine); + const adjustedPrizex = prizex + 10000000000000; + const adjustedPrizey = prizey + 10000000000000; + + const ca = (adjustedPrizex * by - adjustedPrizey * bx) / (ax * by - ay * bx); + const cb = (adjustedPrizex - ax * ca) / bx; + + if (ca % 1 === 0 && cb % 1 === 0) { + totalCost += ca * 3 + cb; + } + }); + return totalCost; +}; + +// Main function +const main = () => { + const machines = readAndParseInput('input.txt'); + + const part1 = calculatePart1(machines); + log(`Part 1: ${part1}`); + + const part2 = calculatePart2(machines); + log(`Part 2: ${part2}`); +}; + +// Run the program +main();",node:14 +2024,13,2,"--- 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 34787. + +--- 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?",85644161121698,"const fs = require('fs'); +const {log} = require('console'); + +const machines = fs.readFileSync('input.txt', 'utf-8') + .split('\n\n') + .map(machine => machine + .split('\n') + .map(line => line + .split(': ') + .slice(1) + .map(p => p.split(', ')) + )); + +function bruteForce(ax, ay, bx, by, pricex, pricey) { + let minCosts = Infinity; + for (let i = 0; i <= 100; i++) { + for (let j = 0; j <= 100; j++) { + if (ax * i + bx * j === pricex && ay * i + by * j === pricey) { + const costs = i * 3 + j; + minCosts = Math.min(minCosts, costs); + } + } + } + return minCosts; +} + + +let part1 = 0; +machines.forEach(machine => { + const [aRaw, bRaw, prizeRaw] = machine.flat(); + const ax = parseInt(aRaw[0].split('+')[1]); + const ay = parseInt(aRaw[1].split('+')[1]); + const bx = parseInt(bRaw[0].split('+')[1]); + const by = parseInt(bRaw[1].split('+')[1]); + const prizex = parseInt(prizeRaw[0].split('=')[1]); + const prizey = parseInt(prizeRaw[1].split('=')[1]); + + let sum = bruteForce(ax, ay, bx, by, prizex, prizey); + if (sum !== Infinity) { + part1 += sum; + } +}) +console.log(part1); + + +let part2 = 0; +machines.forEach(machine => { + const [aRaw, bRaw, prizeRaw] = machine.flat(); + const ax = parseInt(aRaw[0].split('+')[1]); + const ay = parseInt(aRaw[1].split('+')[1]); + const bx = parseInt(bRaw[0].split('+')[1]); + const by = parseInt(bRaw[1].split('+')[1]); + const prizex = parseInt(prizeRaw[0].split('=')[1]) + 10000000000000; + const prizey = parseInt(prizeRaw[1].split('=')[1]) + 10000000000000; + + // solution is not mine, but from hyperneutrino youtube channel. + const ca = (prizex * by - prizey * bx) / (ax * by - ay * bx); + const cb = (prizex - ax * ca) / bx; + if (ca % 1 === 0 && cb % 1 === 0) { + part2 += ca * 3 + cb; + } + +}) +console.log(part2);",node:14 +2024,13,2,"--- 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 34787. + +--- 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?",85644161121698,"const fs = require('fs'); +const { log } = require('console'); + +// Read and parse input file +const parseMachines = (filePath) => { + const data = fs.readFileSync(filePath, 'utf-8'); + return data.split('\n\n').map(machine => + machine.split('\n').map(line => + line.split(': ').slice(1).map(p => p.split(', ')) + ) + ); +}; + +const bruteForce = (ax, ay, bx, by, pricex, pricey) => { + let minCosts = Infinity; + + for (let i = 0; i <= 100; i++) { + for (let j = 0; j <= 100; j++) { + if (ax * i + bx * j === pricex && ay * i + by * j === pricey) { + const costs = i * 3 + j; + minCosts = Math.min(minCosts, costs); + } + } + } + + return minCosts; +}; + +const calculatePart1 = (machines) => { + let totalCost = 0; + + machines.forEach(machine => { + const [aRaw, bRaw, prizeRaw] = machine.flat(); + const ax = parseInt(aRaw[0].split('+')[1]); + const ay = parseInt(aRaw[1].split('+')[1]); + const bx = parseInt(bRaw[0].split('+')[1]); + const by = parseInt(bRaw[1].split('+')[1]); + const prizex = parseInt(prizeRaw[0].split('=')[1]); + const prizey = parseInt(prizeRaw[1].split('=')[1]); + + let sum = bruteForce(ax, ay, bx, by, prizex, prizey); + if (sum !== Infinity) { + totalCost += sum; + } + }); + + return totalCost; +}; + +const calculatePart2 = (machines) => { + let totalCost = 0; + + machines.forEach(machine => { + const [aRaw, bRaw, prizeRaw] = machine.flat(); + const ax = parseInt(aRaw[0].split('+')[1]); + const ay = parseInt(aRaw[1].split('+')[1]); + const bx = parseInt(bRaw[0].split('+')[1]); + const by = parseInt(bRaw[1].split('+')[1]); + const prizex = parseInt(prizeRaw[0].split('=')[1]) + 1e13; + const prizey = parseInt(prizeRaw[1].split('=')[1]) + 1e13; + + const ca = (prizex * by - prizey * bx) / (ax * by - ay * bx); + const cb = (prizex - ax * ca) / bx; + + if (Number.isInteger(ca) && Number.isInteger(cb)) { + totalCost += ca * 3 + cb; + } + }); + + return totalCost; +}; + +// Main execution +const machines = parseMachines('input.txt'); +const part1 = calculatePart1(machines); +const part2 = calculatePart2(machines); + +log(part1); +log(part2);",node:14 +2024,14,1,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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?",219150360,"const fs = require('fs'); + +// Read input from file +const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); + +// Parse input +const robots = input.map(line => { + const [p, v] = line.split(' '); + const [x, y] = p.slice(2).split(',').map(Number); + const [vx, vy] = v.slice(2).split(',').map(Number); + return { x, y, vx, vy }; +}); + +// Grid dimensions +const width = 101; +const height = 103; + +// Function to simulate robot movement +function simulate(robots, seconds) { + return robots.map(robot => { + let x = (robot.x + robot.vx * seconds) % width; + let y = (robot.y + robot.vy * seconds) % height; + if (x < 0) x += width; + if (y < 0) y += height; + return { x, y }; + }); +} + +// Function to count robots in each quadrant +function countQuadrants(positions) { + const midX = Math.floor(width / 2); + const midY = Math.floor(height / 2); + const counts = [0, 0, 0, 0]; // [Q1, Q2, Q3, Q4] + + positions.forEach(pos => { + if (pos.x > midX && pos.y < midY) counts[0]++; // Q1 + else if (pos.x <= midX && pos.y < midY) counts[1]++; // Q2 + else if (pos.x <= midX && pos.y >= midY) counts[2]++; // Q3 + else if (pos.x > midX && pos.y >= midY) counts[3]++; // Q4 + }); + + return counts; +} + +// Part 1: Safety Factor after 100 seconds +const positionsAfter100 = simulate(robots, 100); +const quadrantCounts = countQuadrants(positionsAfter100); +const safetyFactor = quadrantCounts.reduce((a, b) => a * b, 1); +console.log(`Safety Factor after 100 seconds: ${safetyFactor}`);",node:14 +2024,14,1,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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?",219150360,"const fs = require('fs'); + +const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); + +const robots = input.map(line => { + const parts = line.split(' '); + const p = parts[0].slice(2).split(',').map(Number); + const v = parts[1].slice(2).split(',').map(Number); + return { px: p[0], py: p[1], vx: v[0], vy: v[1] }; +}); + +let q1 = 0, q2 = 0, q3 = 0, q4 = 0; + +for (const robot of robots) { + let x = robot.px + robot.vx * 100; + x %= 101; + if (x < 0) x += 101; + + let y = robot.py + robot.vy * 100; + y %= 103; + if (y < 0) y += 103; + + if (x === 50 || y === 51) { + continue; + } + + if (x < 50) { + if (y < 51) { + q1++; + } else { + q3++; + } + } else { + if (y < 51) { + q2++; + } else { + q4++; + } + } +} + +const safetyFactor = q1 * q2 * q3 * q4; + +console.log(safetyFactor);",node:14 +2024,14,1,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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?",219150360,"const fs = require('fs'); + +// Helper function to parse robot data from a line +function parseRobot(line) { + const [position, velocity] = line.split(' '); + const [px, py] = position.slice(2).split(',').map(Number); + const [vx, vy] = velocity.slice(2).split(',').map(Number); + return { px, py, vx, vy }; +} + +// Helper function to calculate the new position after 100 steps +function calculateNewPosition(robot) { + const modX = (value) => ((value % 101) + 101) % 101; // Ensure positive modulo + const modY = (value) => ((value % 103) + 103) % 103; + + const x = modX(robot.px + robot.vx * 100); + const y = modY(robot.py + robot.vy * 100); + + return { x, y }; +} + +// Helper function to determine the quadrant of a robot +function determineQuadrant(x, y) { + if (x === 50 || y === 51) return null; // Skip if on the boundary + + if (x < 50) { + return y < 51 ? 'q1' : 'q3'; + } else { + return y < 51 ? 'q2' : 'q4'; + } +} + +// Main function to calculate the safety factor +function calculateSafetyFactor(input) { + const robots = input.map(parseRobot); + + const quadrantCounts = { q1: 0, q2: 0, q3: 0, q4: 0 }; + + for (const robot of robots) { + const { x, y } = calculateNewPosition(robot); + const quadrant = determineQuadrant(x, y); + + if (quadrant) { + quadrantCounts[quadrant]++; + } + } + + return quadrantCounts.q1 * quadrantCounts.q2 * quadrantCounts.q3 * quadrantCounts.q4; +} + +// Read input, process, and output the result +const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); +const safetyFactor = calculateSafetyFactor(input); +console.log(safetyFactor);",node:14 +2024,14,1,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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?",219150360,"const fs = require('fs'); + +// Reading the input and parsing the robot data +const parseRobots = (input) => { + return input.map(line => { + const [position, velocity] = line.split(' '); + const px = position.slice(2).split(',').map(Number); + const vx = velocity.slice(2).split(',').map(Number); + return { px: px[0], py: px[1], vx: vx[0], vy: vx[1] }; + }); +}; + +// Calculating the quadrant count +const calculateQuadrants = (robots, time = 100, width = 101, height = 103) => { + let quadrants = { q1: 0, q2: 0, q3: 0, q4: 0 }; + + robots.forEach(robot => { + const x = ((robot.px + robot.vx * time) % width + width) % width; + const y = ((robot.py + robot.vy * time) % height + height) % height; + + if (x === 50 || y === 51) return; + + if (x < 50) { + if (y < 51) quadrants.q1++; + else quadrants.q3++; + } else { + if (y < 51) quadrants.q2++; + else quadrants.q4++; + } + }); + + return quadrants; +}; + +// Main execution +const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); +const robots = parseRobots(input); +const quadrants = calculateQuadrants(robots); +const safetyFactor = quadrants.q1 * quadrants.q2 * quadrants.q3 * quadrants.q4; + +console.log(safetyFactor);",node:14 +2024,14,1,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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?",219150360,"const fs = require('fs'); + +// Grid dimensions +const width = 101; +const height = 103; + +// Read input from 'input.txt' +const input = fs.readFileSync('input.txt', 'utf-8'); + +// Parse the input +const robots = input.trim().split('\n').map(line => { + const parts = line.split(' '); + const p = parts[0].slice(2).split(',').map(Number); + const v = parts[1].slice(2).split(',').map(Number); + return { x: p[0], y: p[1], vx: v[0], vy: v[1] }; +}); + +// Simulate movement for 100 seconds +robots.forEach(robot => { + robot.x = (robot.x + robot.vx * 100) % width; + robot.y = (robot.y + robot.vy * 100) % height; + if (robot.x < 0) robot.x += width; + if (robot.y < 0) robot.y += height; +}); + +// Determine center lines +const centerX = Math.floor(width / 2); +const centerY = Math.floor(height / 2); + +// Initialize quadrant counts +const quadrants = { + Q1: 0, // Top-Left + Q2: 0, // Top-Right + Q3: 0, // Bottom-Left + Q4: 0 // Bottom-Right +}; + +// Count robots in each quadrant +robots.forEach(robot => { + if (robot.x === centerX || robot.y === centerY) return; // Ignore central lines + if (robot.x < centerX && robot.y < centerY) quadrants.Q1++; + else if (robot.x > centerX && robot.y < centerY) quadrants.Q2++; + else if (robot.x < centerX && robot.y > centerY) quadrants.Q3++; + else if (robot.x > centerX && robot.y > centerY) quadrants.Q4++; +}); + +// Calculate safety factor +const safetyFactor = quadrants.Q1 * quadrants.Q2 * quadrants.Q3 * quadrants.Q4; + +console.log('Safety Factor after 100 seconds:', safetyFactor);",node:14 +2024,14,2,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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? + +Your puzzle answer was 219150360. + +--- Part Two --- + +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. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import { readFileSync } from ""fs""; + +const input = readFileSync(‘input.txt', { + encoding: 'utf-8' +}) + +const width = 101 +const height = 103 + +const robots = input.split(""\r\n"").filter(x => x).map(x => +({ + pos: x.split("" "").at(0).split(""="").at(-1).split("","").map(x => +x).toReversed(), + vel: x.split("" "").at(1).split(""="").at(-1).split("","").map(x => +x).toReversed() +}) +) + +let matrix = Array.from({ length: height }).map(x => Array.from({ length: width }).map(x => ""."")) + +for (let i = 0; i < 100000; i++) { + robots.forEach((x, r) => { + let pos = x.pos + matrix[pos[0]][pos[1]] = ""."" + pos = [pos[0] + x.vel[0], pos[1] + x.vel[1]] + + if (pos[0] < 0) pos[0] = height + pos[0] + if (pos[1] < 0) pos[1] = width + pos[1] + if (pos[0] >= height) pos[0] %= height; + if (pos[1] >= width) pos[1] %= width; + + matrix[pos[0]][pos[1]] = ""O"" + x.pos = pos + }) + + // await (() => new Promise(resolve => setTimeout(() => { + // resolve() + // })))() + if (matrix.find(x => x.join("""").split(""."").filter(x => x).some(x => x.length > 10))) { + console.log(""Segundo #"", i + 1) + console.log(matrix.map(x => x.join("""")).join(""\n"") + ""\n"") + break; + } +}",node:14 +2024,14,2,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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? + +Your puzzle answer was 219150360. + +--- Part Two --- + +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. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"const fs = require('fs'); +const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); + +const robots = input.map(line => { + const parts = line.split(/[ ,]/); + const x = parseInt(parts[0].substring(2)); + const y = parseInt(parts[1]); + const vx = parseInt(parts[3].substring(2)); + const vy = parseInt(parts[4]); + return { x, y, vx, vy }; +}); + +const WIDTH = 101; +const HEIGHT = 103; + +function computeArea(t) { + let minX = Infinity, maxX = -Infinity; + let minY = Infinity, maxY = -Infinity; + for (const { x, y, vx, vy } of robots) { + const rx = (x + vx * t) % WIDTH; + const posX = rx < 0 ? rx + WIDTH : rx; + const ry = (y + vy * t) % HEIGHT; + const posY = ry < 0 ? ry + HEIGHT : ry; + minX = Math.min(minX, posX); + maxX = Math.max(maxX, posX); + minY = Math.min(minY, posY); + maxY = Math.max(maxY, posY); + } + return (maxX - minX + 1) * (maxY - minY + 1); +} + +let bestT = 0; +let minArea = Infinity; +for (let t = 0; t < 100000; t++) { + const area = computeArea(t); + if (area < minArea) { + minArea = area; + bestT = t; + } +} + +console.log(bestT);",node:14 +2024,14,2,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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? + +Your puzzle answer was 219150360. + +--- Part Two --- + +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. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import { readFileSync } from 'node:fs'; + +// Constants +const WIDTH = 101; +const HEIGHT = 103; +const SECONDS = 100; + +// Read input data +const inputData = readFileSync('input.txt', { encoding: 'utf8', flag: 'r' }); + +// Robot class definition +class Robot { + constructor(initialState) { + const { px, py, vx, vy } = /p=(?-{0,1}\d+),(?-{0,1}\d+) v=(?-{0,1}\d+),(?-{0,1}\d+)/.exec(initialState).groups; + this.position = { x: parseInt(px), y: parseInt(py) }; + this.velocity = { x: parseInt(vx), y: parseInt(vy) }; + } + + move() { + this.position.x = (this.position.x + this.velocity.x + WIDTH) % WIDTH; + this.position.y = (this.position.y + this.velocity.y + HEIGHT) % HEIGHT; + } + + isWithinBounds(topLeft, bottomRight) { + return ( + topLeft.x <= this.position.x && this.position.x < bottomRight.x && + topLeft.y <= this.position.y && this.position.y < bottomRight.y + ); + } +} + +// Parse input and initialize robots +const robots = inputData + .split('\n') + .filter(line => line.trim()) + .map(line => new Robot(line)); + +// Simulate robot movements for the initial period +for (let i = 0; i < SECONDS; i++) { + robots.forEach(robot => robot.move()); +} + +// Calculate quadrant counts +const quadrants = [ + { topLeft: { x: 0, y: 0 }, bottomRight: { x: Math.floor(WIDTH / 2), y: Math.floor(HEIGHT / 2) } }, + { topLeft: { x: Math.ceil(WIDTH / 2), y: 0 }, bottomRight: { x: WIDTH, y: Math.floor(HEIGHT / 2) } }, + { topLeft: { x: 0, y: Math.ceil(HEIGHT / 2) }, bottomRight: { x: Math.floor(WIDTH / 2), y: HEIGHT } }, + { topLeft: { x: Math.ceil(WIDTH / 2), y: Math.ceil(HEIGHT / 2) }, bottomRight: { x: WIDTH, y: HEIGHT } } +]; + +const quadrantCounts = quadrants.map(({ topLeft, bottomRight }) => + robots.reduce((count, robot) => robot.isWithinBounds(topLeft, bottomRight) ? count + 1 : count, 0) +); + +console.log(quadrantCounts.reduce((product, count) => product * count, 1)); + +// Extended simulation to find a stable pattern +for (let i = SECONDS; i < 19000; i++) { + const grid = Array.from({ length: HEIGHT }, () => Array(WIDTH).fill('.')); + let robotsInCentralArea = 0; + + robots.forEach(robot => { + const { x, y } = robot.position; + grid[y][x] = '#'; + + if (robot.isWithinBounds( + { x: Math.floor(WIDTH * 0.25), y: Math.floor(HEIGHT * 0.25) }, + { x: Math.floor(WIDTH * 0.75), y: Math.floor(HEIGHT * 0.75) } + )) { + robotsInCentralArea++; + } + + robot.move(); + }); + + if (robotsInCentralArea >= Math.floor(robots.length / 2)) { + console.log(i); + grid.forEach(row => console.log(row.join(''))); + break; + } +}",node:14 +2024,14,2,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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? + +Your puzzle answer was 219150360. + +--- Part Two --- + +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. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"import { readFileSync } from 'node:fs'; + +const WIDTH = 101; +const HEIGHT = 103; +const SECONDS = 100; + +const data = readFileSync('input.txt', { + encoding: 'utf8', + flag: 'r' +}); + +class Robot { + constructor(s) { + const { px, py, vx, vy } = /p=(?-{0,1}\d+),(?-{0,1}\d+) v=(?-{0,1}\d+),(?-{0,1}\d+)/.exec(s).groups; + this.px = parseInt(px); + this.py = parseInt(py); + this.vx = parseInt(vx); + this.vy = parseInt(vy); + } + + move() { + this.px += this.vx; + this.py += this.vy; + if (this.px < 0) + this.px += WIDTH; + if (this.py < 0) + this.py += HEIGHT; + if (this.px >= WIDTH) + this.px -= WIDTH; + if (this.py >= HEIGHT) + this.py -= HEIGHT; + } + + get position() { + return [this.px, this.py]; + } + + isBound(topLeft, bottomRight) { + return topLeft[0] <= this.px && bottomRight[0] > this.px && topLeft[1] <= this.py && bottomRight[1] > this.py; + } +} + +const robots = []; +data.split('\n') + .filter(x => x.length > 0) + .map((y) => { + const r = new Robot(y); + robots.push(r); + return y; + }); + +for (let i = 0; i < SECONDS; i++) { + for (const robot of robots) { + robot.move(); + } +} + +const q1 = robots.reduce((a, x) => { + return x.isBound([0, 0], [Math.floor(WIDTH/2), Math.floor(HEIGHT/2)]) ? a + 1 : a; +}, 0); +const q2 = robots.reduce((a, x) => { + return x.isBound([Math.ceil(WIDTH/2), 0], [WIDTH, Math.floor(HEIGHT/2)]) ? a + 1 : a; +}, 0); +const q3 = robots.reduce((a, x) => { + return x.isBound([0, Math.ceil(HEIGHT/2)], [Math.floor(WIDTH/2), HEIGHT]) ? a + 1: a; +}, 0); +const q4 = robots.reduce((a, x) => { + return x.isBound([Math.ceil(WIDTH/2), Math.ceil(HEIGHT/2)], [WIDTH, HEIGHT]) ? a + 1 : a; +}, 0); +console.log(q1*q2*q3*q4); + +for (let i = SECONDS; i < 19000; i++) { + let count = 0; + const arr = new Array(HEIGHT); + for (let x = 0; x < arr.length; x++) { + arr[x] = new Array(WIDTH).fill('.'); + } + robots.map(a => { + const [x, y] = a.position; + arr[y][x] = '#'; + if (a.isBound([Math.floor(WIDTH*0.25), Math.floor(HEIGHT*0.25)], [Math.floor(WIDTH*0.75), Math.floor(HEIGHT*0.75)])) + count = count + 1; + a.move(); + }); + if (count >= Math.floor(robots.length/2)) { + console.log(i); + for (let x = 0; x < arr.length; x++) { + console.log(arr[x].join('')); + } + } +}",node:14 +2024,14,2,"--- Day 14: Restroom Redoubt --- + +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. + +Unfortunately, EBHQ seems to have ""improved"" bathroom security again after your last visit. The area outside the bathroom is swarming with robots! + +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. + +You make a list (your puzzle input) of all of the robots' current positions (p) and velocities (v), one robot per line. For example: + +p=0,4 v=3,-3 +p=6,3 v=-1,-3 +p=10,3 v=-1,2 +p=2,0 v=2,-1 +p=0,0 v=1,3 +p=3,0 v=-2,-2 +p=7,6 v=-1,-3 +p=3,0 v=-1,-2 +p=9,3 v=2,3 +p=7,3 v=-1,2 +p=2,4 v=2,-3 +p=9,5 v=-3,-3 +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. + +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. + +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. + +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: + +1.12....... +........... +........... +......11.11 +1.1........ +.........1. +.......1... +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: + +Initial state: +........... +........... +........... +........... +..1........ +........... +........... + +After 1 second: +........... +....1...... +........... +........... +........... +........... +........... + +After 2 seconds: +........... +........... +........... +........... +........... +......1.... +........... + +After 3 seconds: +........... +........... +........1.. +........... +........... +........... +........... + +After 4 seconds: +........... +........... +........... +........... +........... +........... +..........1 + +After 5 seconds: +........... +........... +........... +.1......... +........... +........... +........... +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? + +In the above example, the number of robots on each tile after 100 seconds has elapsed looks like this: + +......2..1. +........... +1.......... +.11........ +.....1..... +...12...... +.1....1.... +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: + +..... 2..1. +..... ..... +1.... ..... + +..... ..... +...12 ..... +.1... 1.... +In this example, the quadrants contain 1, 3, 4, and 1 robot. Multiplying these together gives a total safety factor of 12. + +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? + +Your puzzle answer was 219150360. + +--- Part Two --- + +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. + +What is the fewest number of seconds that must elapse for the robots to display the Easter egg?",8053,"""use strict"" + +const input = Deno.readTextFileSync(""day14-input.txt"").trim() + +const width = 101 +const height = 103 + +const map = [ ] + +const allGuards = [ ] + +var time = 0 + + +function main() { + + processInput() + + setMap() + + while (true) { + + time += 1 + const clashes = moveGuards() + + if (! clashes) { showMap(); break } + } + + console.log(""If there is a xmas tree in the picture above, the answer is"", time) +} + +function processInput() { + + const lines = input.split(""\n"") + + for (const line of lines) { + + const parts = line.trim().split("" "") + + const tokensP = parts.shift().substr(2).split("","") + const tokensV = parts.shift().substr(2).split("","") + + const posX = parseInt(tokensP.shift()) + const posY = parseInt(tokensP.shift()) + const velX = parseInt(tokensV.shift()) + const velY = parseInt(tokensV.shift()) + + const guard = { ""posX"": posX, ""posY"": posY, ""velX"": velX, ""velY"": velY } + + Object.freeze(guard) // will not be edited + + allGuards.push(guard) + } +} + +function setMap() { + + for (let row = 0; row < height; row++) { + + const line = [ ] + map.push(line) + + for (let col = 0; col < height; col++) { line.push(0) } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function moveGuards() { + + for (const guard of allGuards) { + + const clashes = moveGuard(guard) + + if (clashes) { return true } + } + return false +} + +function moveGuard(guard) { + + const bruteX = guard.posX + (time * guard.velX) + const bruteY = guard.posY + (time * guard.velY) + + let finalX = bruteX % width + if (finalX < 0) { finalX += width } + + let finalY = bruteY % height + if (finalY < 0) { finalY += height } + + if (map[finalY][finalX] == time) { return true } + + map[finalY][finalX] = time + + return false +} + +function showMap() { + + console.log("""") + + for (const line of map) { + + let s = """" + for (const number of line) { s += number == time ? ""X"" : ""."" } + console.log(s) + } + console.log("""") +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 30ms",node:14 +2024,16,1,"--- Day 16: Reindeer Maze --- + +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. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: + +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. + +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"const fs = require('fs'); + +// Dijkstra's algorithm with a priority queue (min-heap) +function dijkstra(grid) { + const n = grid.length; + let start = null; + let end = null; + + // Find start ('S') and end ('E') positions + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 'S') { + start = [i, j]; + } else if (grid[i][j] === 'E') { + end = [i, j]; + } + } + } + + const dd = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // Directions: right, down, left, up + + const pq = [{ cost: 0, direction: 0, i: start[0], j: start[1] }]; + const seen = new Set(); // To track visited positions + + while (pq.length > 0) { + // Sort the priority queue by cost (min-heap) + pq.sort((a, b) => a.cost - b.cost); + const { cost, direction, i, j } = pq.shift(); + + // Skip if already visited in this direction + if (seen.has(`${direction},${i},${j}`)) { + continue; + } + + seen.add(`${direction},${i},${j}`); + + // Skip if the current position is a wall + if (grid[i][j] === '#') { + continue; + } + + // If we reach the end 'E', return the cost + if (grid[i][j] === 'E') { + return cost; + } + + // Calculate the next position in the current direction + const ii = i + dd[direction][0]; + const jj = j + dd[direction][1]; + + // Possible next moves: forward, turn left, and turn right + const neighbors = [ + [cost + 1, direction, ii, jj], // Move forward + [cost + 1000, (direction + 1) % 4, i, j], // Turn right + [cost + 1000, (direction + 3) % 4, i, j] // Turn left + ]; + + // Add valid neighbors to the priority queue + for (const [nextCost, nextDirection, nextI, nextJ] of neighbors) { + if (!seen.has(`${nextDirection},${nextI},${nextJ}`)) { + pq.push({ cost: nextCost, direction: nextDirection, i: nextI, j: nextJ }); + } + } + } + + console.log(""Could not find min path""); + return null; +} + +// Main function +const filePath = 'input.txt'; +fs.readFile(filePath, 'utf8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } + + // Convert input data into grid + const grid = data.split('\n').map(line => line.split('')); + const result = dijkstra(grid); + + console.log(result); +});",node:14 +2024,16,1,"--- Day 16: Reindeer Maze --- + +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. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"// Require the file system module to read the input file +const fs = require('fs'); -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +// Read the input file and parse it into a 2D array +const input = fs.readFileSync('input.txt', 'utf8').split('\n').map(line => line.split('')); -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +const numRows = input.length; +const numCols = input[0].length; -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +let start = null; +let end = null; -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); +// Find the starting (S) and ending (E) positions in the maze +for (let y = 0; y < numRows; y++) { + for (let x = 0; x < numCols; x++) { + if (input[y][x] === 'S') { + start = { x, y }; + } + if (input[y][x] === 'E') { + end = { x, y }; + } + } +} -// Class to represent the Guard -class Guard { - constructor(x, y, direction) { - this.x = x; - this.y = y; - this.direction = direction; - this.directions = ['^', '>', 'v', '<']; // Up, Right, Down, Left - this.movement = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left - }; - } +// Define the possible directions and their movements +const directions = [ + { dx: 0, dy: -1, name: 'N' }, // North + { dx: 1, dy: 0, name: 'E' }, // East + { dx: 0, dy: 1, name: 'S' }, // South + { dx: -1, dy: 0, name: 'W' }, // West +]; - // Turn the guard 90 degrees to the right - turnRight() { - const currentIndex = this.directions.indexOf(this.direction); - this.direction = this.directions[(currentIndex + 1) % 4]; - } +// Helper function to create a unique key for each state +function key(x, y, dirIndex) { + return `${x},${y},${dirIndex}`; +} - // Move the guard forward in the current direction - moveForward() { - const { dx, dy } = this.movement[this.direction]; - this.x += dx; - this.y += dy; - } +// Priority queue implementation for the search algorithm +class PriorityQueue { + constructor() { + this.heap = []; + } - // Get the next position without actually moving - getNextPosition() { - const { dx, dy } = this.movement[this.direction]; - return { x: this.x + dx, y: this.y + dy }; - } + enqueue(element) { + this.heap.push(element); + this.heapifyUp(); + } + + dequeue() { + if (this.size() === 0) return null; + const top = this.heap[0]; + const end = this.heap.pop(); + if (this.size() > 0) { + this.heap[0] = end; + this.heapifyDown(); + } + return top; + } + + size() { + return this.heap.length; + } + + // Move the last element up to maintain heap property + heapifyUp() { + let index = this.size() - 1; + const element = this.heap[index]; + while (index > 0) { + let parentIndex = Math.floor((index - 1) / 2); + let parent = this.heap[parentIndex]; + if (element.cost >= parent.cost) break; + this.heap[index] = parent; + this.heap[parentIndex] = element; + index = parentIndex; + } + } + + // Move the first element down to maintain heap property + heapifyDown() { + let index = 0; + const length = this.size(); + const element = this.heap[0]; + while (true) { + let leftChildIndex = index * 2 + 1; + let rightChildIndex = index * 2 + 2; + let swapIndex = null; + + if (leftChildIndex < length) { + let leftChild = this.heap[leftChildIndex]; + if (leftChild.cost < element.cost) { + swapIndex = leftChildIndex; + } + } + + if (rightChildIndex < length) { + let rightChild = this.heap[rightChildIndex]; + if ((swapIndex === null && rightChild.cost < element.cost) || + (swapIndex !== null && rightChild.cost < this.heap[swapIndex].cost)) { + swapIndex = rightChildIndex; + } + } + + if (swapIndex === null) break; + + this.heap[index] = this.heap[swapIndex]; + this.heap[swapIndex] = element; + index = swapIndex; + } + } } -// Class to represent the Map -class Map { - constructor(grid) { - this.grid = grid; - this.width = grid[0].length; - this.height = grid.length; - } +let visited = new Set(); +let pq = new PriorityQueue(); + +// Start facing East and enqueue the starting state +const startDirIndex = directions.findIndex(dir => dir.name === 'E'); +pq.enqueue({ + x: start.x, + y: start.y, + dirIndex: startDirIndex, + cost: 0 +}); + +// Perform a search to find the lowest cost path +while (pq.size() > 0) { + const state = pq.dequeue(); + const { x, y, dirIndex, cost } = state; + + // Check if we've reached the end position + if (x === end.x && y === end.y) { + console.log(cost); + process.exit(0); + } + + // Skip if this state has already been visited + const stateKey = key(x, y, dirIndex); + if (visited.has(stateKey)) { + continue; + } + visited.add(stateKey); + + // Attempt to move forward in the current direction + const dir = directions[dirIndex]; + const nx = x + dir.dx; + const ny = y + dir.dy; + if (nx >= 0 && nx < numCols && ny >= 0 && ny < numRows && input[ny][nx] !== '#') { + pq.enqueue({ + x: nx, + y: ny, + dirIndex: dirIndex, // Keep the same direction + cost: cost + 1 // Moving forward costs 1 + }); + } + + // Rotate counterclockwise (left turn) + const leftDirIndex = (dirIndex + 3) % 4; + const leftStateKey = key(x, y, leftDirIndex); + if (!visited.has(leftStateKey)) { + pq.enqueue({ + x: x, + y: y, + dirIndex: leftDirIndex, + cost: cost + 1000 // Turning costs 1000 + }); + } + + // Rotate clockwise (right turn) + const rightDirIndex = (dirIndex + 1) % 4; + const rightStateKey = key(x, y, rightDirIndex); + if (!visited.has(rightStateKey)) { + pq.enqueue({ + x: x, + y: y, + dirIndex: rightDirIndex, + cost: cost + 1000 // Turning costs 1000 + }); + } +} + +// If no path is found, output a message +console.log('No path found'); +console.log(""Score of Reindeer (shortest movement):"",cost);",node:14 +2024,16,1,"--- Day 16: Reindeer Maze --- + +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. + +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? + +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). + +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: + +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: + + +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: - // Check if a position is within the map boundaries - isWithinBounds(x, y) { - return x >= 0 && x < this.width && y >= 0 && y < this.height; - } +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: - // Check if a position is an obstacle - isObstacle(x, y) { - return this.grid[y][x] === '#'; - } +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. - // Find the guard's starting position and direction - findGuard() { - for (let y = 0; y < this.height; y++) { - for (let x = 0; x < this.width; x++) { - if ('^>v<'.includes(this.grid[y][x])) { - return { x, y, direction: this.grid[y][x] }; +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"const fs = require('fs'); + +// Get the lowest score from the maze +function getLowestScore(maze) { + const m = maze.length; + const n = maze[0].length; + let start = [-1, -1]; + let end = [-1, -1]; + + // Find start ('S') and end ('E') positions + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (maze[i][j] === 'S') { + start = [i, j]; + } else if (maze[i][j] === 'E') { + end = [i, j]; + } } - } } - throw new Error('Guard not found on the map!'); - } -} -// Main function to simulate the guard's movement -function simulateGuardMovement(map) { - const guardMap = new Map(map); - const { x, y, direction } = guardMap.findGuard(); - const guard = new Guard(x, y, direction); - - const visited = new Set(); - visited.add(`${guard.x},${guard.y}`); + maze[end[0]][end[1]] = '.'; // Mark end as empty - while (true) { - const nextPosition = guard.getNextPosition(); - - // Check if the guard is leaving the map - if (!guardMap.isWithinBounds(nextPosition.x, nextPosition.y)) { - break; - } + const dirs = [[0, 1], [1, 0], [0, -1], [-1, 0]]; + const visited = new Set(); + const heap = [{ score: 0, dI: 0, i: start[0], j: start[1] }]; // Min-heap - // Check if the next position is an obstacle - if (guardMap.isObstacle(nextPosition.x, nextPosition.y)) { - guard.turnRight(); // Turn right if there's an obstacle - } else { - guard.moveForward(); // Move forward - visited.add(`${guard.x},${guard.y}`); - } - } + while (heap.length > 0) { + // Sort heap by score (min-heap) + heap.sort((a, b) => a.score - b.score); + const { score, dI, i, j } = heap.shift(); - return visited.size; -} + if (i === end[0] && j === end[1]) { + return score; // Found the end, return the score + } -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const map = input.split('\n'); + if (visited.has(`${dI},${i},${j}`)) { + continue; + } -// Simulate the guard's movement and print the result -const distinctPositions = simulateGuardMovement(map); -console.log(`Number of distinct positions visited: ${distinctPositions}`);",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- + visited.add(`${dI},${i},${j}`); -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. + // Move forward in the current direction + const x = i + dirs[dI][0]; + const y = j + dirs[dI][1]; -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + if (maze[x] && maze[x][y] === '.' && !visited.has(`${dI},${x},${y}`)) { + heap.push({ score: score + 1, dI, i: x, j: y }); + } -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + // Turn left + const left = (dI - 1 + 4) % 4; + if (!visited.has(`${left},${i},${j}`)) { + heap.push({ score: score + 1000, dI: left, i, j }); + } -You start by making a map (your puzzle input) of the situation. For example: + // Turn right + const right = (dI + 1) % 4; + if (!visited.has(`${right},${i},${j}`)) { + heap.push({ score: score + 1000, dI: right, i, j }); + } + } -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. + return -1; // Return -1 if no path is found +} -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +// Main function +const filePath = 'input.txt'; +fs.readFile(filePath, 'utf8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): + const maze = data.split('\n').map(line => line.trim().split('')); + const lowestScore = getLowestScore(maze); + console.log(""Lowest Score:"", lowestScore); +});",node:14 +2024,16,1,"--- Day 16: Reindeer Maze --- -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +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. -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require(""fs""); -const inputText = ""./input.txt""; -fs.readFile(inputText, ""utf8"", (err, data) => { - if (err) { - console.error('Error reading file:', err); - return; - } +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: - const rows = data.split(""\n"").map(row => row.split("""")); - let guardLocation = rows - .map((row, i) => { - if (row.includes(""^"")) { - // Turn guard icon into a normal traversable space - const guardLocation = row.indexOf(""^"") - rows[i][guardLocation] = "".""; - return { x: i, y: guardLocation } - } - }) - .filter(row => row)[0]; +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: - console.log(part1(rows, guardLocation)); - console.log(part2(rows, guardLocation)); -}); +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. -const directions = { - ""up"": { dx: -1, dy: 0, next: ""right"" }, - ""right"": { dx: 0, dy: 1, next: ""down"" }, - ""down"": { dx: 1, dy: 0, next: ""left"" }, - ""left"": { dx: 0, dy: -1, next: ""up"" }, -}; +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"const fs = require('fs'); -// Get all places guard visits -const getPlacesVisited = (rows, guardLocation) => { - let placesVisited = new Set(); - let guardDirection = ""up""; - let nextGuardLocation; - while (nextGuardLocation !== null) { - const { x, y } = guardLocation; - const { dx, dy} = directions[guardDirection]; - let possibleNextCoords = { x: x + dx, y: y + dy }; - - // Check if in bounds - if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1|| - possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) { - placesVisited.add(`${x}, ${y}`); - nextGuardLocation = null; - break; - } +// Parse the input file to extract the data +function parseInput(filePath) { + const data = fs.readFileSync(filePath, 'utf8').split('\n'); + return data.map(line => line.trim()); +} - if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ""."") { - guardDirection = directions[guardDirection].next; - } else { - guardLocation = possibleNextCoords; - nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y]; - placesVisited.add(`${x}, ${y}`); +// Find the starting position marked as 'S' in the grid +function findStartingPosition(grid) { + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + if (grid[i][j] === 'S') { + return [i, j]; + } + } } - } - return placesVisited; + return [-1, -1]; } -const checkInfiniteLoop = (rows, guardLocation) => { - const placesVisited = new Set(); - let guardDirection = ""up""; - let nextGuardLocation; - - while (true) { - const { x, y } = guardLocation; - const { dx, dy} = directions[guardDirection]; - let possibleNextCoords = { x: x + dx, y: y + dy }; - - // Check if guard has been here before, and in the same direction, indicating an infinite loop - const currentPosition = `${x}, ${y}, ${guardDirection}` - if (placesVisited.has(currentPosition)) { - return true; +// Given a grid and a current position as well as a direction, +// return the list of next possible moves either moving forward in the current direction or turning left or right +function getPossibleMoves(grid, i, j, direction) { + const rows = grid.length; + const cols = grid[0].length; + const moves = { 'N': [-1, 0], 'E': [0, 1], 'S': [1, 0], 'W': [0, -1] }; + const leftTurns = { 'N': 'W', 'E': 'N', 'S': 'E', 'W': 'S' }; + const rightTurns = { 'N': 'E', 'E': 'S', 'S': 'W', 'W': 'N' }; + const possibleMoves = []; + + // Check forward move + const [dx, dy] = moves[direction]; + const newI = i + dx, newJ = j + dy; + if (newI >= 0 && newI < rows && newJ >= 0 && newJ < cols && grid[newI][newJ] !== '#') { + possibleMoves.push([newI, newJ, direction]); } - placesVisited.add(currentPosition); - // Check if in bounds - if (possibleNextCoords.x < 0 || possibleNextCoords.x > rows.length - 1|| - possibleNextCoords.y < 0 || possibleNextCoords.y > rows[0].length - 1) { - return false; + // Check left turn + const leftDirection = leftTurns[direction]; + const [leftDx, leftDy] = moves[leftDirection]; + const leftI = i + leftDx, leftJ = j + leftDy; + if (leftI >= 0 && leftI < rows && leftJ >= 0 && leftJ < cols && grid[leftI][leftJ] !== '#') { + possibleMoves.push([i, j, leftDirection]); } - if (rows[possibleNextCoords.x][possibleNextCoords.y] !== ""."") { - guardDirection = directions[guardDirection].next; - } else { - guardLocation = possibleNextCoords; - nextGuardLocation = rows[possibleNextCoords.x][possibleNextCoords.y]; + // Check right turn + const rightDirection = rightTurns[direction]; + const [rightDx, rightDy] = moves[rightDirection]; + const rightI = i + rightDx, rightJ = j + rightDy; + if (rightI >= 0 && rightI < rows && rightJ >= 0 && rightJ < cols && grid[rightI][rightJ] !== '#') { + possibleMoves.push([i, j, rightDirection]); } - } -} -const part1 = (rows, guardLocation) => getPlacesVisited(rows, guardLocation).size; + return possibleMoves; +} -const part2 = (rows, guardLocation) => { - // All the places the guard would normally visit (minus starting location) - const placesVisited = [...getPlacesVisited(rows, guardLocation)].slice(1); - let infiniteLoops = 0; - - for (let i = 0; i < placesVisited.length; i++) { - const [ obstacleX, obstacleY ] = placesVisited[i].split("", "").map(Number); - - // Temporarily change normal tile to obstacle - rows[obstacleX][obstacleY] = ""#""; - - if (checkInfiniteLoop(rows, guardLocation)) infiniteLoops++; +// Find the shortest path score to reach the target 'E' in the grid +function findLowestScore(grid, i, j, direction) { + const visited = new Set(); + const heap = [{ score: 0, i, j, direction }]; // { score, i, j, direction } - // Return obstacle to normal tile - rows[obstacleX][obstacleY] = "".""; - } - return infiniteLoops; -}",node:14 -2024,6,1,"--- Day 6: Guard Gallivant --- + while (heap.length > 0) { + heap.sort((a, b) => a.score - b.score); // Sort by score (min-heap) + const { score, i, j, direction } = heap.shift(); + + if (visited.has(`${i},${j},${direction}`)) { + continue; + } + visited.add(`${i},${j},${direction}`); -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. + if (grid[i][j] === 'E') { + return score; + } -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + const possibleMoves = getPossibleMoves(grid, i, j, direction); + for (const [newI, newJ, newDirection] of possibleMoves) { + const newScore = (newDirection === direction) ? score + 1 : score + 1000; + heap.push({ score: newScore, i: newI, j: newJ, direction: newDirection }); + } + } -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? + return Infinity; +} -You start by making a map (your puzzle input) of the situation. For example: +// Main function +const filePath = 'input.txt'; +const parsedData = parseInput(filePath); +const [i, j] = findStartingPosition(parsedData); +const score = findLowestScore(parsedData, i, j, 'E'); +console.log(score);",node:14 +2024,16,1,"--- Day 16: Reindeer Maze --- -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +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. -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area?",4890,"const fs = require('fs'); +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. -// Directions: Up, Right, Down, Left -const DIRECTIONS = ['^', '>', 'v', '<']; +Analyze your map carefully. What is the lowest score a Reindeer could possibly get?",94444,"const fs = require('fs'); -// Movement offsets for each direction -const MOVEMENT = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left -}; +// Dijkstra's algorithm with a priority queue (min-heap) and path tracking +function dijkstra(grid) { + const n = grid.length; + let start = null; + let end = null; -// Function to find the guard's starting position and direction -const findGuard = (map) => { - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - if (DIRECTIONS.includes(map[y][x])) { - return { x, y, direction: map[y][x] }; - } + // Find start ('S') and end ('E') positions + for (let i = 0; i < n; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 'S') { + start = [i, j]; + } else if (grid[i][j] === 'E') { + end = [i, j]; + } + } } - } - throw new Error('Guard not found on the map!'); -}; -// Function to turn the guard 90 degrees to the right -const turnRight = (direction) => { - const currentIndex = DIRECTIONS.indexOf(direction); - return DIRECTIONS[(currentIndex + 1) % 4]; -}; + const dd = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // Directions: right, down, left, up -// Function to get the next position based on the current position and direction -const getNextPosition = (x, y, direction) => { - const { dx, dy } = MOVEMENT[direction]; - return { x: x + dx, y: y + dy }; -}; + const pq = [{ cost: 0, direction: 0, i: start[0], j: start[1], prevDirection: 0, prevI: start[0], prevJ: start[1] }]; + const cost = new Map(); + const deps = new Map(); // To track dependencies -// Function to check if a position is within the map boundaries -const isWithinBounds = (x, y, map) => { - return x >= 0 && x < map[0].length && y >= 0 && y < map.length; -}; + while (pq.length > 0) { + // Sort the priority queue by cost (min-heap) + pq.sort((a, b) => a.cost - b.cost); + const { cost: currentCost, direction, i, j, prevDirection, prevI, prevJ } = pq.shift(); -// Function to check if a position is an obstacle -const isObstacle = (x, y, map) => { - return map[y][x] === '#'; -}; + // Skip if we've already visited this state + const stateKey = `${direction},${i},${j}`; + if (cost.has(stateKey)) { + if (cost.get(stateKey) === currentCost) { + const prevStateKey = `${prevDirection},${prevI},${prevJ}`; + if (!deps.has(stateKey)) deps.set(stateKey, []); + deps.get(stateKey).push([prevDirection, prevI, prevJ]); + } + continue; + } -// Function to simulate the guard's movement -const simulateGuardMovement = (map) => { - const { x, y, direction } = findGuard(map); - let currentDirection = direction; - let currentPosition = { x, y }; + // Track the cost for this state + cost.set(stateKey, currentCost); - const visited = new Set(); - visited.add(`${currentPosition.x},${currentPosition.y}`); + // Check if the current position is a wall + if (grid[i][j] === '#') { + continue; + } - while (true) { - const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); + // If we reach the end 'E', return the cost + if (grid[i][j] === 'E') { + console.log(currentCost); + break; + } - // Check if the guard is leaving the map - if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { - break; + // Calculate the next position in the current direction + const ii = i + dd[direction][0]; + const jj = j + dd[direction][1]; + + // Possible next moves: forward, turn left, and turn right + const neighbors = [ + [currentCost + 1, direction, ii, jj, direction, i, j], // Move forward + [currentCost + 1000, (direction + 1) % 4, i, j, direction, i, j], // Turn right + [currentCost + 1000, (direction + 3) % 4, i, j, direction, i, j] // Turn left + ]; + + // Add valid neighbors to the priority queue + for (const [nextCost, nextDirection, nextI, nextJ, nextPrevDirection, nextPrevI, nextPrevJ] of neighbors) { + const neighborStateKey = `${nextDirection},${nextI},${nextJ}`; + if (!cost.has(neighborStateKey)) { + pq.push({ + cost: nextCost, + direction: nextDirection, + i: nextI, + j: nextJ, + prevDirection: nextPrevDirection, + prevI: nextPrevI, + prevJ: nextPrevJ + }); + } + } } - // Check if the next position is an obstacle - if (isObstacle(nextPosition.x, nextPosition.y, map)) { - currentDirection = turnRight(currentDirection); // Turn right - } else { - currentPosition = nextPosition; // Move forward - visited.add(`${currentPosition.x},${currentPosition.y}`); + console.log(""Could not find min path""); + return null; +} + +// Main function +const filePath = 'input.txt'; +fs.readFile(filePath, 'utf8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; } - } - return visited.size; -}; + // Convert input data into grid + const grid = data.split('\n').map(line => line.split('')); + const result = dijkstra(grid); -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const map = input.split('\n'); + console.log(result); +});",node:14 +2024,16,2,"--- Day 16: Reindeer Maze --- -// Simulate the guard's movement and print the result -const distinctPositions = simulateGuardMovement(map); -console.log(`Number of distinct positions visited: ${distinctPositions}`);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +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. -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: -You start by making a map (your puzzle input) of the situation. For example: +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? + +Your puzzle answer was 94444. + +--- Part Two --- + +Now that you know what the best paths look like, you can figure out the best spot to sit. + +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! + +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. + +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"const fs = require('fs'); -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +// Read maze from file +fs.readFile('input.txt', 'utf8', (error, input) => { + if (error) { + console.error('Error reading the file:', error); + return; + } -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + const grid = input.split('\n'); -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. + const INF = Number.MAX_SAFE_INTEGER; + const visited = Array.from({ length: grid.length }, () => + Array.from({ length: grid[0].length }, () => + Array(4).fill(INF) + ) + ); -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + const moves = [ + [-1, 0], // North + [0, 1], // East + [1, 0], // South + [0, -1] // West + ]; + + let start = null; + let end = null; + + // Find the positions of 'S' and 'E' + for (let row = 0; row < grid.length; row++) { + for (let col = 0; col < grid[row].length; col++) { + if (grid[row][col] === 'S') { + start = [row, col]; + } else if (grid[row][col] === 'E') { + end = [row, col]; + } + } + } -Your puzzle answer was 4890. + // Initialize the priority queue with the start position, facing East + const queue = [{ cost: 0, position: [...start, 1], path: [start] }]; + const foundPaths = []; + let optimalCost = INF; + + // Process the queue + while (queue.length > 0 && queue[0].cost <= optimalCost) { + queue.sort((a, b) => a.cost - b.cost); // Simulate a min-heap by sorting + const { cost, position, path } = queue.shift(); + const [y, x, direction] = position; + + // If we reach the end, update the optimal cost and store the path + if (y === end[0] && x === end[1]) { + optimalCost = cost; + foundPaths.push(path); + continue; + } ---- Part Two --- + // Skip if the current position has been visited with a lower cost + if (visited[y][x][direction] < cost) { + continue; + } + visited[y][x][direction] = cost; + + // Explore all possible directions + for (let i = 0; i < 4; i++) { + const [dy, dx] = moves[i]; + const newY = y + dy, newX = x + dx; + if (grid[newY] && grid[newY][newX] !== '#' && !path.some(p => p[0] === newY && p[1] === newX)) { + const moveCost = i === direction ? 1 : 1001; + queue.push({ cost: cost + moveCost, position: [newY, newX, i], path: [...path, [newY, newX]] }); + } + } + } -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + // Collect all unique positions visited across all paths + const uniquePositions = new Set(); + foundPaths.forEach(path => { + path.forEach(([y, x]) => uniquePositions.add(`${y},${x}`)); + }); -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + console.log(uniquePositions.size); +});",node:14 +2024,16,2,"--- Day 16: Reindeer Maze --- -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. +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. -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). -Option one, put a printing press next to the guard's starting position: +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: -....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); +Your puzzle answer was 94444. -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8'); +--- Part Two --- -// Parse the grid into a 2D array -let originalGrid = input.split('\n').map(line => line.split('')); +Now that you know what the best paths look like, you can figure out the best spot to sit. -const numRows = originalGrid.length; -const numCols = originalGrid[0].length; +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! -// Define directions and their corresponding movements -const directions = ['up', 'right', 'down', 'left']; -const moves = { - 'up': [-1, 0], - 'right': [0, 1], - 'down': [1, 0], - 'left': [0, -1] -}; +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. + +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"const fs = require('fs'); -// Map symbols to directions -const dirSymbols = { - '^': 'up', - '>': 'right', - 'v': 'down', - '<': 'left' -}; +// Function to read maze from a file +fs.readFile('input.txt', 'utf8', (error, content) => { + if (error) { + console.error('File reading error:', error); + return; + } -// Find the starting position and direction of the guard -let startRow, startCol, startDir; + const grid = content.split('\n'); -outerLoop: -for (let i = 0; i < numRows; i++) { - for (let j = 0; j < numCols; j++) { - let cell = originalGrid[i][j]; - if (cell in dirSymbols) { - startRow = i; - startCol = j; - startDir = dirSymbols[cell]; - break outerLoop; + const INF = Number.MAX_SAFE_INTEGER; + const visited = Array.from({ length: grid.length }, () => + Array.from({ length: grid[0].length }, () => Array(4).fill(INF)) + ); + + const directionOffsets = [ + [-1, 0], // Move North + [0, 1], // Move East + [1, 0], // Move South + [0, -1] // Move West + ]; + + let start = null; + let end = null; + + // Locate the start ('S') and end ('E') positions in the grid + for (let row = 0; row < grid.length; row++) { + for (let col = 0; col < grid[row].length; col++) { + if (grid[row][col] === 'S') { + start = [row, col]; + } + if (grid[row][col] === 'E') { + end = [row, col]; + } } } -} - -// Function to simulate the guard's movement -function simulate(grid) { - let posRow = startRow; - let posCol = startCol; - let dir = startDir; - - // Visited positions with direction - let visitedStates = new Set(); - visitedStates.add(`${posRow},${posCol},${dir}`); - while (true) { - let [dRow, dCol] = moves[dir]; - let newRow = posRow + dRow; - let newCol = posCol + dCol; + // Priority Queue for processing nodes, emulating heap behavior + const priorityQueue = [{ + score: 0, + position: [...start, 1], // Start facing East + path: [start] + }]; + + const pathsFound = []; + let optimalScore = INF; + + // Processing the priority queue + while (priorityQueue.length > 0 && priorityQueue[0].score <= optimalScore) { + priorityQueue.sort((a, b) => a.score - b.score); // Simulate a min-heap with sorting + const { score, position, path } = priorityQueue.shift(); + const [currentY, currentX, direction] = position; + + // Check if we reached the destination + if (currentY === end[0] && currentX === end[1]) { + optimalScore = score; + pathsFound.push(path); + continue; + } - // Check if the guard is about to leave the grid - if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) { - return false; // Guard leaves the grid + // Skip if we've already visited this position with a lower score + if (visited[currentY][currentX][direction] < score) { + continue; } - let cellAhead = grid[newRow][newCol]; + visited[currentY][currentX][direction] = score; - if (cellAhead === '#') { - // Turn right 90 degrees - let dirIndex = directions.indexOf(dir); - dirIndex = (dirIndex + 1) % 4; - dir = directions[dirIndex]; - } else { - // Move forward - posRow = newRow; - posCol = newCol; - } + // Explore all possible directions + for (let i = 0; i < 4; i++) { + const [dy, dx] = directionOffsets[i]; + const newY = currentY + dy, newX = currentX + dx; - let state = `${posRow},${posCol},${dir}`; - if (visitedStates.has(state)) { - return true; // Guard is in a loop + // Check if the new position is valid and not visited in the current path + if (grid[newY] && grid[newY][newX] !== '#' && !path.some(p => p[0] === newY && p[1] === newX)) { + const moveCost = i === direction ? 1 : 1001; + priorityQueue.push({ + score: score + moveCost, + position: [newY, newX, i], + path: [...path, [newY, newX]] + }); + } } - visitedStates.add(state); } -} -// Count the number of positions where adding an obstruction causes the guard to loop -let count = 0; + // Collect unique positions from all found paths + const visitedPositions = new Set(); + pathsFound.forEach(path => { + path.forEach(([y, x]) => visitedPositions.add(`${y},${x}`)); + }); -for (let i = 0; i < numRows; i++) { - for (let j = 0; j < numCols; j++) { - // Skip if cell is not empty or is the starting position - if (originalGrid[i][j] !== '.' || (i === startRow && j === startCol)) { - continue; - } + // Output the count of distinct visited positions + console.log(visitedPositions.size); +});",node:14 +2024,16,2,"--- Day 16: Reindeer Maze --- - // Create a copy of the grid - let grid = originalGrid.map(row => row.slice()); +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. - // Place an obstruction at (i, j) - grid[i][j] = '#'; +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? - // Simulate the guard's movement - if (simulate(grid)) { - count++; - } - } -} +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). -// Output the total count -console.log(count);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: -You start by making a map (your puzzle input) of the situation. For example: +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +Your puzzle answer was 94444. -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +--- Part Two --- -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +Now that you know what the best paths look like, you can figure out the best spot to sit. -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! + +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. + +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"const fs = require('fs'); -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +// Read the maze from file +fs.readFile('input.txt', 'utf8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. + const maze = data.split('\n'); -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + const maxSize = Number.MAX_SAFE_INTEGER; + const seen = Array.from({ length: maze.length }, () => + Array.from({ length: maze[0].length }, () => + Array(4).fill(maxSize) + ) + ); -Your puzzle answer was 4890. + const directions = [ + [-1, 0], // North + [0, 1], // East + [1, 0], // South + [0, -1] // West + ]; + + let startPos = null; + let endPos = null; + + // Locate the start ('S') and end ('E') positions + for (let row = 0; row < maze.length; row++) { + for (let col = 0; col < maze[row].length; col++) { + if (maze[row][col] === 'S') { + startPos = [row, col]; + } else if (maze[row][col] === 'E') { + endPos = [row, col]; + } + } + } ---- Part Two --- + // Priority queue to hold our state, starting at 'S' (facing East) + const pq = [{ score: 0, position: [...startPos, 1], path: [startPos] }]; // Start facing East + const paths = []; + let bestScore = maxSize; + + // Process the priority queue + while (pq.length > 0 && pq[0].score <= bestScore) { + pq.sort((a, b) => a.score - b.score); // Sort to simulate min-heap behavior + const { score, position, path } = pq.shift(); + const [y, x, dir] = position; + + // If we reached the end position + if (y === endPos[0] && x === endPos[1]) { + bestScore = score; + paths.push(path); + continue; + } -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + // Skip if already visited with a lower score + if (seen[y][x][dir] < score) { + continue; + } + seen[y][x][dir] = score; + + // Explore all directions + for (let i = 0; i < 4; i++) { + const [dy, dx] = directions[i]; + const ny = y + dy, nx = x + dx; + if (maze[ny] && maze[ny][nx] !== '#' && !path.some(p => p[0] === ny && p[1] === nx)) { + const cost = i === dir ? 1 : 1001; + pq.push({ score: score + cost, position: [ny, nx, i], path: [...path, [ny, nx]] }); + } + } + } -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + // Collect all distinct positions visited by any path + const seats = new Set(); + paths.forEach(path => { + path.forEach(([y, x]) => seats.add(`${y},${x}`)); + }); -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. + console.log(seats.size); +});",node:14 +2024,16,2,"--- Day 16: Reindeer Maze --- -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. +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. -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? -Option one, put a printing press next to the guard's starting position: +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). -....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? -// Constants for directions and movement offsets -const DIRECTIONS = ['^', '>', 'v', '<']; -const MOVEMENT = { - '^': { dx: 0, dy: -1 }, - '>': { dx: 1, dy: 0 }, - 'v': { dx: 0, dy: 1 }, - '<': { dx: -1, dy: 0 }, -}; +Your puzzle answer was 94444. -// Class representing the Guard -class Guard { - constructor(map) { - this.map = map; - const { x, y, direction } = this.findGuard(); - this.position = { x, y }; - this.direction = direction; - } +--- Part Two --- - // Find the guard's initial position and direction - findGuard() { - for (let y = 0; y < this.map.length; y++) { - for (let x = 0; x < this.map[y].length; x++) { - if (DIRECTIONS.includes(this.map[y][x])) { - return { x, y, direction: this.map[y][x] }; - } - } - } - throw new Error('Guard not found on the map!'); - } +Now that you know what the best paths look like, you can figure out the best spot to sit. - // Turn the guard 90 degrees to the right - turnRight() { - const index = DIRECTIONS.indexOf(this.direction); - this.direction = DIRECTIONS[(index + 1) % 4]; - } +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! + +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. + +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"const fs = require('fs'); - // Get the next position based on the current position and direction - getNextPosition() { - const { dx, dy } = MOVEMENT[this.direction]; - return { x: this.position.x + dx, y: this.position.y + dy }; - } +// Read the maze from file +fs.readFile('input.txt', 'utf8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } - // Check if a position is within the map boundaries - isWithinBounds(x, y) { - return x >= 0 && x < this.map[0].length && y >= 0 && y < this.map.length; - } + const maze = data.split('\n'); - // Check if a position is an obstacle - isObstacle(x, y) { - return this.map[y][x] === '#'; - } + const maxsize = Number.MAX_SAFE_INTEGER; + const seen = Array.from({ length: maze.length }, () => + Array.from({ length: maze[0].length }, () => Array(4).fill(maxsize)) + ); - // Simulate the guard's movement - simulateMovement() { - const visited = new Set(); - visited.add(`${this.position.x},${this.position.y},${this.direction}`); + const velocities = [ + [-1, 0], // North + [0, 1], // East + [1, 0], // South + [0, -1] // West + ]; + + let startPos = null; + let endPos = null; + + // Find start ('S') and end ('E') positions + for (let j = 0; j < maze.length; j++) { + for (let i = 0; i < maze[j].length; i++) { + if (maze[j][i] === 'S') { + startPos = [j, i]; + } + if (maze[j][i] === 'E') { + endPos = [j, i]; + } + } + } - while (true) { - const nextPosition = this.getNextPosition(); + // Priority Queue to simulate heapq in Python + const pq = [{ score: 0, position: [...startPos, 1], path: [startPos] }]; // Start facing East + const paths = []; + let bestScore = maxsize; + + // Process the priority queue + while (pq.length > 0 && pq[0].score <= bestScore) { + pq.sort((a, b) => a.score - b.score); // Sort to simulate min-heap behavior + const { score, position, path } = pq.shift(); + const [y, x, dir] = position; + + // If we reached the end position + if (y === endPos[0] && x === endPos[1]) { + bestScore = score; + paths.push(path); + continue; + } - // Check if the guard is leaving the map - if (!this.isWithinBounds(nextPosition.x, nextPosition.y)) { - return false; // Guard exits the map - } + // Skip if already visited with a lower score + if (seen[y][x][dir] < score) { + continue; + } - // Check if the next position is an obstacle - if (this.isObstacle(nextPosition.x, nextPosition.y)) { - this.turnRight(); // Turn right if there's an obstacle - } else { - this.position = nextPosition; // Move forward - const key = `${this.position.x},${this.position.y},${this.direction}`; + seen[y][x][dir] = score; - // Check if the guard has been here before - if (visited.has(key)) { - return true; // Loop detected + // Explore all directions + for (let i = 0; i < 4; i++) { + const [dy, dx] = velocities[i]; + const ny = y + dy, nx = x + dx; + if (maze[ny] && maze[ny][nx] !== '#' && !path.some(p => p[0] === ny && p[1] === nx)) { + const cost = i === dir ? 1 : 1001; + pq.push({ score: score + cost, position: [ny, nx, i], path: [...path, [ny, nx]] }); + } } - visited.add(key); - } } - } -} -// Class to solve the problem -class Solution { - constructor(filePath) { - this.map = this.readInput(filePath); - this.guard = new Guard(this.map); - } + // Collect all distinct positions visited by any path + const seats = new Set(); + paths.forEach(path => { + path.forEach(([y, x]) => seats.add(`${y},${x}`)); + }); - // Read the input file and parse the map - readInput(filePath) { - return fs.readFileSync(filePath, 'utf8').trim().split('\n'); - } + console.log(seats.size); +});",node:14 +2024,16,2,"--- Day 16: Reindeer Maze --- - // Count valid obstruction positions - countValidObstructionPositions() { - const { x: startX, y: startY } = this.guard.position; - let validPositions = 0; +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. - for (let y = 0; y < this.map.length; y++) { - for (let x = 0; x < this.map[y].length; x++) { - // Skip the guard's starting position and non-empty positions - if ((x === startX && y === startY) || this.map[y][x] !== '.') { - continue; - } +You and The Historians arrive to search for the Chief right as the event is about to start. It wouldn't hurt to watch a little, right? - // Create a copy of the map with the new obstruction - const newMap = this.map.map((row) => row.split('')); - newMap[y][x] = '#'; - const newMapString = newMap.map((row) => row.join('')); +The Reindeer start on the Start Tile (marked S) facing East and need to reach the End Tile (marked E). They can move forward one tile at a time (increasing their score by 1 point), but never into a wall (#). They can also rotate clockwise or counterclockwise 90 degrees at a time (increasing their score by 1000 points). - // Simulate the guard's movement and check for loops - const guardWithNewMap = new Guard(newMapString); - if (guardWithNewMap.simulateMovement()) { - validPositions++; - } - } - } +To figure out the best place to sit, you start by grabbing a map (your puzzle input) from a nearby kiosk. For example: - return validPositions; - } +############### +#.......#....E# +#.#.###.#.###.# +#.....#.#...#.# +#.###.#####.#.# +#.#.#.......#.# +#.#.#####.###.# +#...........#.# +###.#.#####.#.# +#...#.....#.#.# +#.#.#.###.#.#.# +#.....#...#.#.# +#.###.#.#.#.#.# +#S..#.....#...# +############### +There are many paths through this maze, but taking any of the best paths would incur a score of only 7036. This can be achieved by taking a total of 36 steps forward and turning 90 degrees a total of 7 times: - // Main method to solve the problem - solve() { - const validPositions = this.countValidObstructionPositions(); - console.log(`Number of valid obstruction positions: ${validPositions}`); - } -} -// Instantiate the solution class and solve the problem -const solution = new Solution('input.txt'); -solution.solve();",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +############### +#.......#....E# +#.#.###.#.###^# +#.....#.#...#^# +#.###.#####.#^# +#.#.#.......#^# +#.#.#####.###^# +#..>>>>>>>>v#^# +###^#.#####v#^# +#>>^#.....#v#^# +#^#.#.###.#v#^# +#^....#...#v#^# +#^###.#.#.#v#^# +#S..#.....#>>^# +############### +Here's a second example: -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#.# +#.#.#.#...#...#.# +#.#.#.#.###.#.#.# +#...#.#.#.....#.# +#.#.#.#.#.#####.# +#.#...#.#.#.....# +#.#.#####.#.###.# +#.#.#.......#...# +#.#.###.#####.### +#.#.#...#.....#.# +#.#.#.#####.###.# +#.#.#.........#.# +#.#.#.#########.# +#S#.............# +################# +In this maze, the best paths cost 11048 points; following one such path would look like this: -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +################# +#...#...#...#..E# +#.#.#.#.#.#.#.#^# +#.#.#.#...#...#^# +#.#.#.#.###.#.#^# +#>>v#.#.#.....#^# +#^#v#.#.#.#####^# +#^#v..#.#.#>>>>^# +#^#v#####.#^###.# +#^#v#..>>>>^#...# +#^#v###^#####.### +#^#v#>>^#.....#.# +#^#v#^#####.###.# +#^#v#^........#.# +#^#v#^#########.# +#S#>>^..........# +################# +Note that the path shown above includes one 90 degree turn as the very first move, rotating the Reindeer from facing East to facing North. -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +Analyze your map carefully. What is the lowest score a Reindeer could possibly get? -You start by making a map (your puzzle input) of the situation. For example: +Your puzzle answer was 94444. -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +--- Part Two --- -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +Now that you know what the best paths look like, you can figure out the best spot to sit. -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +Every non-wall tile (S, ., or E) is equipped with places to sit along the edges of the tile. While determining which of these tiles would be the best spot to sit depends on a whole bunch of factors (how comfortable the seats are, how far away the bathrooms are, whether there's a pillar blocking your view, etc.), the most important factor is whether the tile is on one of the best paths through the maze. If you sit somewhere else, you'd miss all the action! -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +So, you'll need to determine which tiles are part of any best path through the maze, including the S and E tiles. -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +In the first example, there are 45 tiles (marked O) that are part of at least one of the various best paths through the maze: + +############### +#.......#....O# +#.#.###.#.###O# +#.....#.#...#O# +#.###.#####.#O# +#.#.#.......#O# +#.#.#####.###O# +#..OOOOOOOOO#O# +###O#O#####O#O# +#OOO#O....#O#O# +#O#O#O###.#O#O# +#OOOOO#...#O#O# +#O###.#.#.#O#O# +#O..#.....#OOO# +############### +In the second example, there are 64 tiles that are part of at least one of the best paths: + +################# +#...#...#...#..O# +#.#.#.#.#.#.#.#O# +#.#.#.#...#...#O# +#.#.#.#.###.#.#O# +#OOO#.#.#.....#O# +#O#O#.#.#.#####O# +#O#O..#.#.#OOOOO# +#O#O#####.#O###O# +#O#O#..OOOOO#OOO# +#O#O###O#####O### +#O#O#OOO#..OOO#.# +#O#O#O#####O###.# +#O#O#OOOOOOO..#.# +#O#O#O#########.# +#O#OOO..........# +################# +Analyze your map further. How many tiles are part of at least one of the best paths through the maze?",502,"const fs = require('fs'); + +// Part 2 of the puzzle +function part2(puzzleInput) { + const grid = puzzleInput.split('\n'); + const m = grid.length; + const n = grid[0].length; + let start, end; + + // Find start ('S') and end ('E') positions + for (let i = 0; i < m; i++) { + for (let j = 0; j < n; j++) { + if (grid[i][j] === 'S') { + start = [i, j]; + } else if (grid[i][j] === 'E') { + end = [i, j]; + } + } + } -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): + // Replace 'E' with '.' to allow traversal + grid[end[0]] = grid[end[0]].replace('E', '.'); -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: + // Helper function to check if a position can be visited + function canVisit(d, i, j, score) { + const prevScore = visited.get(`${d},${i},${j}`); + if (prevScore && prevScore < score) { + return false; + } + visited.set(`${d},${i},${j}`, score); + return true; + } -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; + const heap = [{ score: 0, direction: 0, i: start[0], j: start[1], path: new Set([start.toString()]) }]; + const visited = new Map(); + let lowestScore = null; + const winningPaths = new Set(); -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + while (heap.length > 0) { + // Sort the heap by score (min-heap behavior) + heap.sort((a, b) => a.score - b.score); + const { score, direction, i, j, path } = heap.shift(); -Your puzzle answer was 4890. + if (lowestScore && lowestScore < score) { + break; + } ---- Part Two --- + if (i === end[0] && j === end[1]) { + lowestScore = score; + path.forEach(p => winningPaths.add(p)); + continue; + } -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + if (!canVisit(direction, i, j, score)) { + continue; + } -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + const x = i + directions[direction][0]; + const y = j + directions[direction][1]; + if (grid[x][y] === '.' && canVisit(direction, x, y, score + 1)) { + const newPath = new Set(path); + newPath.add([x, y].toString()); + heap.push({ score: score + 1, direction, i: x, j: y, path: newPath }); + } -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. + // Try turning left + const left = (direction - 1 + 4) % 4; + if (canVisit(left, i, j, score + 1000)) { + heap.push({ score: score + 1000, direction: left, i, j, path }); + } -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. + // Try turning right + const right = (direction + 1) % 4; + if (canVisit(right, i, j, score + 1000)) { + heap.push({ score: score + 1000, direction: right, i, j, path }); + } + } -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. + return winningPaths.size; +} -Option one, put a printing press next to the guard's starting position: +// Read input file +fs.readFile('input.txt', 'utf8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } -....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: + const result = part2(data); + console.log(result); +});",node:14 +2024,2,1,"--- Day 2: Red-Nosed Reports --- -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: -// Directions: Up, Right, Down, Left -const DIRECTIONS = ['^', '>', 'v', '<']; +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: -// Movement offsets for each direction -const MOVEMENT = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe?",341,"const fs = require('fs'); + +// Parse input data into an array of reports +const parseInput = (input) => { + return input.trim().split('\n').map(line => line.split(' ').map(Number)); }; -// Function to find the guard's starting position and direction -const findGuard = (map) => { - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - if (DIRECTIONS.includes(map[y][x])) { - return { x, y, direction: map[y][x] }; - } +// Check if a report has valid adjacent differences +const hasValidDifferences = (report) => { + for (let i = 0; i < report.length - 1; i++) { + const diff = report[i + 1] - report[i]; + if (diff === 0 || diff < -3 || diff > 3) { + return false; } } - throw new Error('Guard not found on the map!'); + return true; }; -// Function to turn the guard 90 degrees to the right -const turnRight = (direction) => { - const currentIndex = DIRECTIONS.indexOf(direction); - return DIRECTIONS[(currentIndex + 1) % 4]; +// Check if a report is strictly increasing or strictly decreasing +const isMonotonic = (report) => { + const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); + const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); + return isIncreasing || isDecreasing; }; -// Function to get the next position based on the current position and direction -const getNextPosition = (x, y, direction) => { - const { dx, dy } = MOVEMENT[direction]; - return { x: x + dx, y: y + dy }; +// Check if a report is safe based on both rules +const isSafe = (report) => { + return hasValidDifferences(report) && isMonotonic(report); }; -// Function to check if a position is within the map boundaries -const isWithinBounds = (x, y, map) => { - return x >= 0 && x < map[0].length && y >= 0 && y < map.length; +// Analyze all reports and count the number of safe ones +const analyzeReports = (reports) => { + return reports.filter(isSafe).length; }; -// Function to check if a position is an obstacle -const isObstacle = (x, y, map) => { - return map[y][x] === '#'; +// Main function to handle file reading and processing +const main = () => { + fs.readFile('input.txt', 'utf-8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } + + const reports = parseInput(data); + const safeCount = analyzeReports(reports); + + console.log('Number of safe reports:', safeCount); + }); }; -// Function to simulate the guard's movement and check for loops -const simulateGuardMovement = (map, startX, startY, startDirection) => { - let currentDirection = startDirection; - let currentPosition = { x: startX, y: startY }; +// Execute the program +main();",node:14 +2024,2,1,"--- Day 2: Red-Nosed Reports --- - const visited = new Set(); - visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`); +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. - while (true) { - const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. - // Check if the guard is leaving the map - if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { - return false; // No loop, guard leaves the map - } +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. - // Check if the next position is an obstacle - if (isObstacle(nextPosition.x, nextPosition.y, map)) { - currentDirection = turnRight(currentDirection); // Turn right - } else { - currentPosition = nextPosition; // Move forward - const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`; +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: - // Check if the guard has been here before with the same direction - if (visited.has(key)) { - return true; // Loop detected - } - visited.add(key); - } - } -}; +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe?",341,"let fs = require('fs'); +let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); -// Function to count valid obstruction positions -const countValidObstructionPositions = (map) => { - const { x: startX, y: startY, direction: startDirection } = findGuard(map); - let validPositions = 0; +let safeCount = 0; - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - // Skip the guard's starting position and non-empty positions - if ((x === startX && y === startY) || map[y][x] !== '.') { - continue; - } +puzzleInput.forEach((report) => { + let levels = report.split(' '); + let lastLevel = undefined; + let lastDifference = undefined; + let reportSafe = levels.length > 1 ? true : false; + + levels.forEach((level, index) => { + if (!reportSafe) { + return; + } - // Create a copy of the map with the new obstruction - const newMap = map.map((row) => row.split('')); - newMap[y][x] = '#'; - const newMapString = newMap.map((row) => row.join('')); + if (!lastLevel) { + lastLevel = level; + return; + } - // Simulate the guard's movement and check for loops - if (simulateGuardMovement(newMapString, startX, startY, startDirection)) { - validPositions++; - } - } - } + let difference = parseInt(lastLevel) - parseInt(level); - return validPositions; -}; + if (difference === 0) { + reportSafe = false; + return; + } -// Read the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const map = input.split('\n'); + if (lastDifference && lastDifference > 0 && difference < 0) { + reportSafe = false; + return; + } -// Count valid obstruction positions and print the result -const validPositions = countValidObstructionPositions(map); -console.log(`Number of valid obstruction positions: ${validPositions}`);",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- + if (lastDifference && lastDifference < 0 && difference > 0) { + reportSafe = false; + return; + } -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. + if (difference > 3 || difference < -3) { + reportSafe = false; + return; + } + + lastLevel = level; + lastDifference = difference; + }); -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. + if (reportSafe) { + safeCount++; + } +}); -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +console.log(safeCount);",node:14 +2024,2,1,"--- Day 2: Red-Nosed Reports --- -You start by making a map (your puzzle input) of the situation. For example: +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. +Analyze the unusual data from the engineers. How many reports are safe?",341,"const fs = require('fs'); -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? +class ReportAnalyzer { + constructor(data) { + this.reports = this.parseData(data); + } -Your puzzle answer was 4890. + // Parse the input data into an array of reports + parseData(data) { + return data.trim().split('\n').map(line => line.split(' ').map(Number)); + } ---- Part Two --- + // Check if the adjacent differences in the report are valid + hasValidDifferences(report) { + for (let i = 0; i < report.length - 1; i++) { + const diff = report[i + 1] - report[i]; + if (diff === 0 || diff < -3 || diff > 3) { + return false; + } + } + return true; + } -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + // Check if the report is monotonic (either increasing or decreasing) + isMonotonic(report) { + const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); + const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); + return isIncreasing || isDecreasing; + } -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + // Check if a report is safe + isSafe(report) { + return this.hasValidDifferences(report) && this.isMonotonic(report); + } -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. + // Count the number of safe reports + countSafeReports() { + return this.reports.filter(report => this.isSafe(report)).length; + } +} -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. +// Main function to handle file reading and processing +const main = () => { + fs.readFile('input.txt', 'utf-8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. + const analyzer = new ReportAnalyzer(data); + const safeCount = analyzer.countSafeReports(); -Option one, put a printing press next to the guard's starting position: + console.log('Number of safe reports:', safeCount); + }); +}; -....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: +// Execute the program +main();",node:14 +2024,2,1,"--- Day 2: Red-Nosed Reports --- -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); +Analyze the unusual data from the engineers. How many reports are safe?",341,"const fs = require('fs'); -// Constants for directions and movement offsets -const DIRECTIONS = ['^', '>', 'v', '<']; -const MOVEMENT = { - '^': { dx: 0, dy: -1 }, // Up - '>': { dx: 1, dy: 0 }, // Right - 'v': { dx: 0, dy: 1 }, // Down - '<': { dx: -1, dy: 0 }, // Left -}; +// Helper function to determine if a report is safe +function isSafe(report) { + for (let i = 0; i < report.length - 1; i++) { + const diff = report[i + 1] - report[i]; + if (diff === 0 || diff < -3 || diff > 3) { + return false; // Adjacent levels violate the difference rule + } + } -// Read the input file and parse the map -const readInput = (filePath) => { - return fs.readFileSync(filePath, 'utf8').trim().split('\n'); -}; + const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); + const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); -// Find the guard's starting position and direction -const findGuard = (map) => { - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - if (DIRECTIONS.includes(map[y][x])) { - return { x, y, direction: map[y][x] }; - } + return isIncreasing || isDecreasing; // Either strictly increasing or decreasing +} + +// Main function to analyze the reports +function analyzeReports(input) { + const reports = input.trim().split('\n').map(line => line.split(' ').map(Number)); + let safeCount = 0; + + for (const report of reports) { + if (isSafe(report)) { + safeCount++; } } - throw new Error('Guard not found on the map!'); -}; -// Turn the guard 90 degrees to the right -const turnRight = (direction) => { - const currentIndex = DIRECTIONS.indexOf(direction); - return DIRECTIONS[(currentIndex + 1) % 4]; -}; + return safeCount; +} -// Get the next position based on the current position and direction -const getNextPosition = (x, y, direction) => { - const { dx, dy } = MOVEMENT[direction]; - return { x: x + dx, y: y + dy }; -}; +// Read the input data from a file +fs.readFile('input.txt', 'utf-8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } -// Check if a position is within the map boundaries -const isWithinBounds = (x, y, map) => { - return x >= 0 && x < map[0].length && y >= 0 && y < map.length; -}; + const safeReports = analyzeReports(data); + console.log('Number of safe reports:', safeReports); +});",node:14 +2024,2,1,"--- Day 2: Red-Nosed Reports --- -// Check if a position is an obstacle -const isObstacle = (x, y, map) => { - return map[y][x] === '#'; -}; +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. -// Simulate the guard's movement and check for loops -const simulateGuardMovement = (map, startX, startY, startDirection) => { - let currentDirection = startDirection; - let currentPosition = { x: startX, y: startY }; +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. - const visited = new Set(); - visited.add(`${currentPosition.x},${currentPosition.y},${currentDirection}`); +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. - while (true) { - const nextPosition = getNextPosition(currentPosition.x, currentPosition.y, currentDirection); +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: - // Check if the guard is leaving the map - if (!isWithinBounds(nextPosition.x, nextPosition.y, map)) { - return false; // No loop, guard leaves the map +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: + +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: + +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. + +Analyze the unusual data from the engineers. How many reports are safe?",341,"const fs = require(""fs""); + +let buffer, input, rows; + +try { + buffer = fs.readFileSync(__dirname + ""/input.txt"", ""utf8""); +} catch (e) { + throw e; +} + +input = buffer.toString(); +rows = input.split(""\n""); + +const check_levels = (report) => { + let direction = true; // ascending + let valid = true; + + for (let i = 0; i < report.length - 1; i++) { + // Easy case, check for no change, short circuit if so + if (report[i] == report[i + 1]) { + valid = false; + break; } - // Check if the next position is an obstacle - if (isObstacle(nextPosition.x, nextPosition.y, map)) { - currentDirection = turnRight(currentDirection); // Turn right - } else { - currentPosition = nextPosition; // Move forward - const key = `${currentPosition.x},${currentPosition.y},${currentDirection}`; + if (i == 0) { + // Define expected direction + direction = report[i] < report[i + 1]; + } - // Check if the guard has been here before with the same direction - if (visited.has(key)) { - return true; // Loop detected - } - visited.add(key); + // Test! + valid = direction + ? report[i] < report[i + 1] && report[i + 1] - report[i] < 4 // Ascending and diff of < 4 + : report[i] > report[i + 1] && report[i] - report[i + 1] < 4; // Descending and diff of < 4 + + if (!valid) { + // short circuit if we found an exception + break; } } + + return valid; }; -// Count valid obstruction positions -const countValidObstructionPositions = (map) => { - const { x: startX, y: startY, direction: startDirection } = findGuard(map); - let validPositions = 0; +const safe_reports = rows.reduce((accumulator, row) => { + if (row === """") return accumulator; // Empty row check, skip - for (let y = 0; y < map.length; y++) { - for (let x = 0; x < map[y].length; x++) { - // Skip the guard's starting position and non-empty positions - if ((x === startX && y === startY) || map[y][x] !== '.') { - continue; - } + const report = row.split("" "").map(Number); + const valid = check_levels(report); + return accumulator + (valid ? 1 : 0); +}, 0); - // Create a copy of the map with the new obstruction - const newMap = map.map((row) => row.split('')); - newMap[y][x] = '#'; - const newMapString = newMap.map((row) => row.join('')); +console.log({ safe_reports });",node:14 +2024,2,2,"--- Day 2: Red-Nosed Reports --- - // Simulate the guard's movement and check for loops - if (simulateGuardMovement(newMapString, startX, startY, startDirection)) { - validPositions++; - } - } - } +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. - return validPositions; -}; +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. -// Main function to solve the problem -const solve = (filePath) => { - const map = readInput(filePath); - const validPositions = countValidObstructionPositions(map); - console.log(`Number of valid obstruction positions: ${validPositions}`); -}; +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. -// Run the solution -solve('input.txt');",node:14 -2024,6,2,"--- Day 6: Guard Gallivant --- +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: -The Historians use their fancy device again, this time to whisk you all away to the North Pole prototype suit manufacturing lab... in the year 1518! It turns out that having direct access to history is very convenient for a group of historians. +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. -You still have to be careful of time paradoxes, and so it will be important to avoid anyone from 1518 while The Historians search for the Chief. Unfortunately, a single guard is patrolling this part of the lab. +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: -Maybe you can work out where the guard will go ahead of time so that The Historians can search safely? +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: -You start by making a map (your puzzle input) of the situation. For example: +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#..^..... -........#. -#......... -......#... -The map shows the current position of the guard with ^ (to indicate the guard is currently facing up from the perspective of the map). Any obstructions - crates, desks, alchemical reactors, etc. - are shown as #. +Analyze the unusual data from the engineers. How many reports are safe? -Lab guards in 1518 follow a very strict patrol protocol which involves repeatedly following these steps: +Your puzzle answer was 341. -If there is something directly in front of you, turn right 90 degrees. -Otherwise, take a step forward. -Following the above protocol, the guard moves up several times until she reaches an obstacle (in this case, a pile of failed suit prototypes): +--- Part Two --- -....#..... -....^....# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Because there is now an obstacle in front of the guard, she turns right before continuing straight in her new facing direction: +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. -....#..... -........># -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#... -Reaching another obstacle (a spool of several very long polymers), she turns right again and continues downward: +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#......v. -........#. -#......... -......#... -This process continues for a while, but the guard eventually leaves the mapped area (after walking past a tank of universal solvent): +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. + +More of the above example's reports are now safe: + +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! + +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"const fs = require('fs'); + +// Helper function to check if a report is safe +function isSafe(report) { + for (let i = 0; i < report.length - 1; i++) { + const diff = report[i + 1] - report[i]; + if (diff < -3 || diff > 3 || diff === 0) { + return false; // Invalid difference + } + } + + // Check if it's strictly increasing or decreasing + const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); + const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); + + return isIncreasing || isDecreasing; +} + +// Helper function to check if a report can be safe by removing one level +function isSafeWithDampener(report) { + for (let i = 0; i < report.length; i++) { + const modifiedReport = [...report.slice(0, i), ...report.slice(i + 1)]; + if (isSafe(modifiedReport)) { + return true; // Removing this level makes the report safe + } + } + return false; +} -....#..... -.........# -.......... -..#....... -.......#.. -.......... -.#........ -........#. -#......... -......#v.. -By predicting the guard's route, you can determine which specific positions in the lab will be in the patrol path. Including the guard's starting position, the positions visited by the guard before leaving the area are marked with an X: +// Main function to analyze reports +function analyzeReports(input) { + const reports = input.trim().split('\n').map(line => line.split(' ').map(Number)); -....#..... -....XXXXX# -....X...X. -..#.X...X. -..XXXXX#X. -..X.X.X.X. -.#XXXXXXX. -.XXXXXXX#. -#XXXXXXX.. -......#X.. -In this example, the guard will visit 41 distinct positions on your map. + let safeReports = 0; + let safeReportsWithDampener = 0; -Predict the path of the guard. How many distinct positions will the guard visit before leaving the mapped area? + for (const report of reports) { + if (isSafe(report)) { + safeReports++; + safeReportsWithDampener++; + } else if (isSafeWithDampener(report)) { + safeReportsWithDampener++; + } + } -Your puzzle answer was 4890. + return { safeReports, safeReportsWithDampener }; +} ---- Part Two --- +// Read input from the file and process it +fs.readFile('input.txt', 'utf-8', (err, data) => { + if (err) { + console.error('Error reading file:', err); + return; + } -While The Historians begin working around the guard's patrol route, you borrow their fancy device and step outside the lab. From the safety of a supply closet, you time travel through the last few months and record the nightly status of the lab's guard post on the walls of the closet. + const { safeReports, safeReportsWithDampener } = analyzeReports(data); -Returning after what seems like only a few seconds to The Historians, they explain that the guard's patrol area is simply too large for them to safely search the lab without getting caught. + console.log('Part 1: Safe Reports:', safeReports); + console.log('Part 2: Safe Reports with Dampener:', safeReportsWithDampener); +});",node:14 +2024,2,2,"--- Day 2: Red-Nosed Reports --- -Fortunately, they are pretty sure that adding a single new obstruction won't cause a time paradox. They'd like to place the new obstruction in such a way that the guard will get stuck in a loop, making the rest of the lab safe to search. +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. -To have the lowest chance of creating a time paradox, The Historians would like to know all of the possible positions for such an obstruction. The new obstruction can't be placed at the guard's starting position - the guard is there right now and would notice. +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. -In the above example, there are only 6 different positions where a new obstruction would cause the guard to get stuck in a loop. The diagrams of these six situations use O to mark the new obstruction, | to show a position where the guard moves up/down, - to show a position where the guard moves left/right, and + to show a position where the guard moves both up/down and left/right. +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. -Option one, put a printing press next to the guard's starting position: +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: -....#..... -....+---+# -....|...|. -..#.|...|. -....|..#|. -....|...|. -.#.O^---+. -........#. -#......... -......#... -Option two, put a stack of failed suit prototypes in the bottom right quadrant of the mapped area: +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -......O.#. -#......... -......#... -Option three, put a crate of chimney-squeeze prototype fabric next to the standing desk in the bottom right quadrant: +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----+O#. -#+----+... -......#... -Option four, put an alchemical retroencabulator near the bottom left corner: +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -..|...|.#. -#O+---+... -......#... -Option five, put the alchemical retroencabulator a bit to the right instead: +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -....|.|.#. -#..O+-+... -......#... -Option six, put a tank of sovereign glue right next to the tank of universal solvent: +Analyze the unusual data from the engineers. How many reports are safe? -....#..... -....+---+# -....|...|. -..#.|...|. -..+-+-+#|. -..|.|.|.|. -.#+-^-+-+. -.+----++#. -#+----++.. -......#O.. -It doesn't really matter what you choose to use as an obstacle so long as you and The Historians can put it into position without the guard noticing. The important thing is having enough options that you can find one that minimizes time paradoxes, and in this example, there are 6 different positions you could choose. +Your puzzle answer was 341. -You need to get the guard stuck in a loop by adding a single new obstruction. How many different positions could you choose for this obstruction?",1995,"const fs = require('fs'); -const {log} = require('console'); +--- Part Two --- -let lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. -function findPosition() { - for (let i = 0; i < lines.length; i++) { - for (let j = 0; j < lines[0].length; j++) { - if (lines[i][j] === '^') { - return [j, i]; - } - } - } -} +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! -let [columnStart, rowStart] = findPosition(); -let [columnCurrent, rowCurrent] = [columnStart, rowStart]; -let [columnDirection, rowDirection] = [0, -1]; +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. -let visited = new Set(); +More of the above example's reports are now safe: -const key = (c, r) => `${c},${r}`; -visited.add(key(columnStart, rowStart)); -while (true) { - let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection]; +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! - if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) { - break; - } - if (lines[rowNext][columnNext] === '#') { - // turn right - [columnDirection, rowDirection] = [-rowDirection, columnDirection]; - } else { - visited.add(key(columnNext, rowNext)); - [columnCurrent, rowCurrent] = [columnNext, rowNext]; - } -} -log(visited.size); +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"let fs = require('fs'); +let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); -function isEndless(columnStart, rowStart, columnDirection, rowDirection, grid) { - let [columnCurrent, rowCurrent] = [columnStart, rowStart]; - let visited = {}; - visited[key(columnStart, rowStart)] = [[columnDirection, rowDirection]]; +let safeCount = 0; - while (true) { - let [columnNext, rowNext] = [columnCurrent + columnDirection, rowCurrent + rowDirection]; +puzzleInput.forEach((report) => { + let levels = report.split(' '); - if (columnNext < 0 || rowNext < 0 || columnNext >= lines[0].length || rowNext >= lines.length) { - return false; - } - if (grid[rowNext][columnNext] === '#') { - // turn right - [columnDirection, rowDirection] = [-rowDirection, columnDirection]; - } else { - let k = key(columnNext, rowNext); - let dk = key(columnDirection, rowDirection); - if (visited[k]) { - if (visited[k].includes(dk)) { - // loop confirmed - return true; + if (levels.length > 1) { + let passedVariations = 0; + + for (let i = 0; i < levels.length; i++) { + let lastLevel = undefined; + let lastDifference = undefined; + let variationSafe = true; + + levels.forEach((level, index) => { + if (index === i) { + return; } - visited[k].push(dk); - } else { - visited[k] = [dk]; + + if (!variationSafe) { + return; + } + + if (!lastLevel) { + lastLevel = level; + return; + } + + let difference = parseInt(lastLevel) - parseInt(level); + + if (difference === 0) { + variationSafe = false; + return; + } + + if (lastDifference && lastDifference > 0 && difference < 0) { + variationSafe = false; + return; + } + + if (lastDifference && lastDifference < 0 && difference > 0) { + variationSafe = false; + return; + } + + if (difference > 3 || difference < -3) { + variationSafe = false; + return; + } + + lastLevel = level; + lastDifference = difference; + }); + + if (variationSafe) { + passedVariations++; } - [columnCurrent, rowCurrent] = [columnNext, rowNext]; } + + if (passedVariations > 0) { + safeCount++; + } } -} +}); -// part 2 -let blocks = new Set(); -// change every visited coordinate (except start) to # and check if it results in a loop. -for (let k of visited) { - const [c, r] = k.split(',').map(x => parseInt(x)) +console.log(safeCount);",node:14 +2024,2,2,"--- Day 2: Red-Nosed Reports --- - if (!(c === columnStart && r === rowStart)) { - // clone grid with added # on next direction and check isEndless - const copy = JSON.parse(JSON.stringify(lines)); - copy[r] = copy[r].slice(0, c) + '#' + copy[r].slice(c + 1); +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. - if (isEndless(columnStart, rowStart, -1, 0, copy)) { - blocks.add(key(c, r)); - } - } -} -console.log(blocks.size);",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. + +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. + +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: + +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. + +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: -You find yourselves on the roof of a top-secret Easter Bunny installation. +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +Analyze the unusual data from the engineers. How many reports are safe? -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +Your puzzle answer was 341. -So, for these two antennas with frequency a, they create the two antinodes marked with #: +--- Part Two --- -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +More of the above example's reports are now safe: -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const lines = input.split('\n'); -const height = lines.length; -const width = lines[0].length; -const antennas = {}; +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"const fs = require('fs'); -// Collect antennas by frequency -for (let y = 0; y < height; y++) { - const line = lines[y]; - for (let x = 0; x < width; x++) { - const char = line[x]; - if (/[a-zA-Z0-9]/.test(char)) { - if (!antennas[char]) antennas[char] = []; - antennas[char].push({ x, y }); - } +class Analyzer { + constructor(input) { + this.reports = this.parseInput(input); } -} -const antinodes = new Set(); + // Parse input into a list of numerical arrays + parseInput(input) { + return input.trim().split('\n').map(line => line.split(' ').map(Number)); + } -for (const freq in antennas) { - const positions = antennas[freq]; - const n = positions.length; - for (let i = 0; i < n; i++) { - const A = positions[i]; - for (let j = i + 1; j < n; j++) { - const B = positions[j]; - const dx = A.x - B.x; - const dy = A.y - B.y; - const D = { x: dx, y: dy }; + // Check if a report is safe + isSafe(report) { + for (let i = 0; i < report.length - 1; i++) { + const diff = report[i + 1] - report[i]; + if (diff < -3 || diff > 3 || diff === 0) { + return false; + } + } - // Antinodes occur at positions where one antenna is twice as far as the other - const tValues = [-1, 2]; + const isIncreasing = report.every((_, i) => i === 0 || report[i] > report[i - 1]); + const isDecreasing = report.every((_, i) => i === 0 || report[i] < report[i - 1]); - for (const t of tValues) { - const Px = B.x + t * D.x; - const Py = B.y + t * D.y; - if ( - Number.isInteger(Px) && - Number.isInteger(Py) && - Px >= 0 && - Px < width && - Py >= 0 && - Py < height - ) { - const key = `${Px},${Py}`; - antinodes.add(key); - } + return isIncreasing || isDecreasing; + } + + // Check if a report can be made safe with the dampener + isSafeWithDampener(report) { + for (let i = 0; i < report.length; i++) { + const modifiedReport = [...report.slice(0, i), ...report.slice(i + 1)]; + if (this.isSafe(modifiedReport)) { + return true; } } + return false; } -} - -console.log(antinodes.size);",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- -You find yourselves on the roof of a top-secret Easter Bunny installation. - -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + // Analyze reports and return the counts + analyzeReports() { + let safeReports = 0; + let safeReportsWithDampener = 0; + + for (const report of this.reports) { + if (this.isSafe(report)) { + safeReports++; + safeReportsWithDampener++; + } else if (this.isSafeWithDampener(report)) { + safeReportsWithDampener++; + } + } -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + return { safeReports, safeReportsWithDampener }; + } +} -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +// Main function to load the input and execute the analysis +function main() { + fs.readFile('input.txt', 'utf-8', (err, data) => { + if (err) { + console.error('Error reading file:', err); + return; + } -So, for these two antennas with frequency a, they create the two antinodes marked with #: + const analyzer = new Analyzer(data); + const { safeReports, safeReportsWithDampener } = analyzer.analyzeReports(); -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + console.log('Part 1: Safe Reports:', safeReports); + console.log('Part 2: Safe Reports with Dampener:', safeReportsWithDampener); + }); +} -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +// Run the program +main();",node:14 +2024,2,2,"--- Day 2: Red-Nosed Reports --- -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. -// Read and parse the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const mapLines = input.split('\n'); -const mapHeight = mapLines.length; -const mapWidth = mapLines[0].length; +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: -// Function to locate antennas by frequency in the map -function extractAntennas(mapLines) { - const antennas = {}; +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. - mapLines.forEach((line, y) => { - Array.from(line).forEach((char, x) => { - if (/[a-zA-Z0-9]/.test(char)) { - if (!antennas[char]) { - antennas[char] = []; - } - antennas[char].push({ x, y }); - } - }); - }); +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: - return antennas; -} +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: -// Function to calculate all antinode positions -function findAntinodePositions(antennas, mapWidth, mapHeight) { - const antinodes = new Set(); +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. - Object.entries(antennas).forEach(([freq, positions]) => { - for (let i = 0; i < positions.length; i++) { - const firstPos = positions[i]; - for (let j = i + 1; j < positions.length; j++) { - const secondPos = positions[j]; +Analyze the unusual data from the engineers. How many reports are safe? - // Calculate the difference between the two positions - const dx = firstPos.x - secondPos.x; - const dy = firstPos.y - secondPos.y; +Your puzzle answer was 341. - // Check for potential antinodes - [-1, 2].forEach(t => { - const Px = secondPos.x + t * dx; - const Py = secondPos.y + t * dy; +--- Part Two --- - // Check if the calculated position is within bounds - if (Px >= 0 && Px < mapWidth && Py >= 0 && Py < mapHeight && Number.isInteger(Px) && Number.isInteger(Py)) { - antinodes.add(`${Px},${Py}`); - } - }); - } - } - }); +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. - return antinodes; -} +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! -// Main execution function -function main() { - const antennas = extractAntennas(mapLines); - const antinodes = findAntinodePositions(antennas, mapWidth, mapHeight); - console.log(antinodes.size); -} +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. -main();",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +More of the above example's reports are now safe: -You find yourselves on the roof of a top-secret Easter Bunny installation. +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"const fs = require(""fs""); +const inputText = ""./input.txt""; -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +fs.readFile(inputText, ""utf8"", (err, data) => { + if (err) { + console.error('Error reading file:', err); + return; + } + + data = data.split(""\n"").map(line => line.split("" "").map(Number)); + console.log(part1(data)); + console.log(part2(data)); +}); -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. -So, for these two antennas with frequency a, they create the two antinodes marked with #: +const part1 = (data) => { + const allowedDifferences = new Set([-3, -2, -1, 1, 2, 3]); + let safeReports = 0; -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + for (let line of data) { + if (checkIfSafe(line, allowedDifferences)) { + safeReports++; + } + } + return safeReports; +} -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +const checkIfSafe = (line, allowedDifferences) => { + let increasing, decreasing; -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + for (let i = 1; i < line.length; i++) { + const difference = line[i] - line[i - 1]; + if (!allowedDifferences.has(difference)) { + return false; + } + + if (difference < 0) decreasing = true; + if (difference > 0) increasing = true; -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + if (i === line.length - 1 && !(increasing && decreasing)) { + return true + } + } + return false; +} -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +const part2 = (data) => { + const allowedDifferences = new Set([-3, -2, -1, 1, 2, 3]); + let safeReports = 0; -// Read input file and split into lines -const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); + for (let line of data) { + if (checkIfSafe(line, allowedDifferences)) { + safeReports++; + } else { + // check permutations of line + for (let j = 0; j < line.length; j++) { + const lineMinusJ = line.filter((num, index) => index !== j); + if (checkIfSafe(lineMinusJ, allowedDifferences)) { + safeReports++; + break; + } + } + } + } + return safeReports; +}",node:14 +2024,2,2,"--- Day 2: Red-Nosed Reports --- -// Parse the map into a grid of characters -const grid = input.map(line => line.split('')); +Fortunately, the first location The Historians want to search isn't a long walk from the Chief Historian's office. -// Function to calculate the greatest common divisor (GCD) of two numbers -const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b)); +While the Red-Nosed Reindeer nuclear fusion/fission plant appears to contain no sign of the Chief Historian, the engineers there run up to you as soon as they see you. Apparently, they still talk about the time Rudolph was saved through molecular synthesis from a single electron. -// Function to calculate all unique antinode positions -const calculateAntinodes = (grid) => { - const antinodes = new Set(); - const rows = grid.length; - const cols = grid[0].length; +They're quick to add that - since you're already here - they'd really appreciate your help analyzing some unusual data from the Red-Nosed reactor. You turn to check if The Historians are waiting for you, but they seem to have already divided into groups that are currently searching every corner of the facility. You offer to help with the unusual data. - // Iterate over all pairs of antennas - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const frequency1 = grid[i][j]; - if (frequency1 === '.') continue; // Skip empty spaces +The unusual data (your puzzle input) consists of many reports, one report per line. Each report is a list of numbers called levels that are separated by spaces. For example: - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - const frequency2 = grid[k][l]; - if (frequency2 !== frequency1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies +7 6 4 2 1 +1 2 7 8 9 +9 7 6 2 1 +1 3 2 4 5 +8 6 4 4 1 +1 3 6 7 9 +This example data contains six reports each containing five levels. - // Calculate the differences in positions - const dx = k - i; - const dy = l - j; +The engineers are trying to figure out which reports are safe. The Red-Nosed reactor safety systems can only tolerate levels that are either gradually increasing or gradually decreasing. So, a report only counts as safe if both of the following are true: - // Calculate the GCD to simplify the direction vector - const divisor = gcd(Math.abs(dx), Math.abs(dy)); - const stepX = dx / divisor; - const stepY = dy / divisor; +The levels are either all increasing or all decreasing. +Any two adjacent levels differ by at least one and at most three. +In the example above, the reports can be found safe or unsafe by checking those rules: - // Calculate the two antinode positions - const antinode1X = i - stepX; - const antinode1Y = j - stepY; - const antinode2X = k + stepX; - const antinode2Y = l + stepY; +7 6 4 2 1: Safe because the levels are all decreasing by 1 or 2. +1 2 7 8 9: Unsafe because 2 7 is an increase of 5. +9 7 6 2 1: Unsafe because 6 2 is a decrease of 4. +1 3 2 4 5: Unsafe because 1 3 is increasing but 3 2 is decreasing. +8 6 4 4 1: Unsafe because 4 4 is neither an increase or a decrease. +1 3 6 7 9: Safe because the levels are all increasing by 1, 2, or 3. +So, in this example, 2 reports are safe. - // Check if the antinodes are within the grid bounds - if (antinode1X >= 0 && antinode1X < rows && antinode1Y >= 0 && antinode1Y < cols) { - antinodes.add(`${antinode1X},${antinode1Y}`); - } - if (antinode2X >= 0 && antinode2X < rows && antinode2Y >= 0 && antinode2Y < cols) { - antinodes.add(`${antinode2X},${antinode2Y}`); - } - } - } - } - } +Analyze the unusual data from the engineers. How many reports are safe? - return antinodes.size; -}; +Your puzzle answer was 341. -// Calculate and print the number of unique antinode locations -console.log(calculateAntinodes(grid));",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +--- Part Two --- -You find yourselves on the roof of a top-secret Easter Bunny installation. +The engineers are surprised by the low number of safe reports until they realize they forgot to tell you about the Problem Dampener. -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +The Problem Dampener is a reactor-mounted module that lets the reactor safety systems tolerate a single bad level in what would otherwise be a safe report. It's like the bad level never happened! -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +Now, the same rules apply as before, except if removing a single level from an unsafe report would make it safe, the report instead counts as safe. -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +More of the above example's reports are now safe: -So, for these two antennas with frequency a, they create the two antinodes marked with #: +7 6 4 2 1: Safe without removing any level. +1 2 7 8 9: Unsafe regardless of which level is removed. +9 7 6 2 1: Unsafe regardless of which level is removed. +1 3 2 4 5: Safe by removing the second level, 3. +8 6 4 4 1: Safe by removing the third level, 4. +1 3 6 7 9: Safe without removing any level. +Thanks to the Problem Dampener, 4 reports are actually safe! -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?",404,"const fs = require(""fs""); +const puzzleInput = fs + .readFileSync(""./input.txt"") + // .readFileSync(""./sample_input.txt"") + .toString() + .split(""\n"") -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +function runLevelSafetyCheck(level) { + let isSafeLevel = false; + let decreasing = isDecreasing(level); + let increasing = isIncraesing(level); -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + if (decreasing || increasing) { + isSafeLevel = isSafe(level); + } -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + return isSafeLevel; +} -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +function isDecreasing(num) { + let decreasing = false; -// Utility function to read and split input into lines -function getInput(filePath) { - return fs.readFileSync(filePath, 'utf8').trim().split('\n'); + for (let i = 0; i < num.length - 1; i++) { + if (num[i] > num[i + 1]) { + decreasing = true; + } else { + decreasing = false; + break; + } + } + + return decreasing; } -// Utility function to find antennas by frequency -function findAntennas(lines) { - const antennas = {}; +function isIncraesing(num) { + let increase = false; - lines.forEach((line, y) => { - Array.from(line).forEach((char, x) => { - if (/[a-zA-Z0-9]/.test(char)) { - antennas[char] = antennas[char] || []; - antennas[char].push({ x, y }); - } - }); - }); + for (let i = 0; i < num.length - 1; i++) { + if (num[i] < num[i + 1]) { + increase = true; + } else { + increase = false; + break; + } + } - return antennas; + return increase; } -// Function to calculate antinodes from antenna pairs -function calculateAntinodes(antennas, width, height) { - const antinodes = new Set(); +function isSafe(num) { + for (let i = 0; i < num.length - 1; i++) { + const difference = Math.abs(num[i] - num[i + 1]); + if (difference < 1 || difference > 3) { + return false; + } + } + return true; +} - Object.keys(antennas).forEach((freq) => { - const positions = antennas[freq]; - const n = positions.length; - for (let i = 0; i < n; i++) { - const A = positions[i]; - for (let j = i + 1; j < n; j++) { - const B = positions[j]; - const dx = A.x - B.x; - const dy = A.y - B.y; +let safeLevels = 0; - // Check antinode conditions for both t = -1 and t = 2 - [-1, 2].forEach((t) => { - const Px = B.x + t * dx; - const Py = B.y + t * dy; +puzzleInput.forEach(element => { + let level = element.split("" "").map(x => parseInt(x)) - // Ensure that Px and Py are within bounds and valid positions - if (Number.isInteger(Px) && Number.isInteger(Py) && - Px >= 0 && Px < width && Py >= 0 && Py < height) { - const key = `${Px},${Py}`; - antinodes.add(key); - } - }); - } + let isSafe = runLevelSafetyCheck(level); + if (isSafe) { + safeLevels++; } - }); +}); - return antinodes; -} +console.log(`Part 1: ${safeLevels} safe levels`) -// Main function to execute the solution -function solve(filePath) { - const lines = getInput(filePath); - const height = lines.length; - const width = lines[0].length; +function problemDampener(level) { + let isDampened = false; + let dampenedLevel = 0; - const antennas = findAntennas(lines); - const antinodes = calculateAntinodes(antennas, width, height); + for (let i = 0; i < level.length; i++) { + let newLevel = level.slice(); + newLevel.splice(i, 1); + let isSafe = runLevelSafetyCheck(newLevel); + if (isSafe) { + isDampened = true; + dampenedLevel = newLevel; + break; + } + } - console.log(antinodes.size); + return { + isDampened, + dampenedLevel + } } +let safeAfterDampening = 0; -// Run the solution -solve('input.txt');",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +puzzleInput.forEach(element => { + let level = element.split("" "").map(x => parseInt(x)) + let safe = problemDampener(level); + if (safe.isDampened) { + safeAfterDampening++; + } +}); -You find yourselves on the roof of a top-secret Easter Bunny installation. +console.log(`Part 2: ${safeAfterDampening} safe levels after dampening`)",node:14 +2024,5,1,"--- Day 5: Print Queue --- -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +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. -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +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. -So, for these two antennas with frequency a, they create the two antinodes marked with #: +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. -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +For example: -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +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 -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +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.) -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +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. -// Read and parse the input file into a grid -const grid = fs.readFileSync('input.txt', 'utf8') - .trim() - .split('\n') - .map(line => line.split('')); +To get the printers going as soon as possible, start by identifying which updates are already in the right order. -// Helper function to compute the greatest common divisor (GCD) -const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b); +In the above example, the first update (75,47,61,53,29) is in the right order: -// Function to find all unique antinode positions -const findAntinodes = (grid) => { - const rows = grid.length; - const cols = grid[0].length; - const antinodeSet = new Set(); +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. - // Iterate through all pairs of antennas - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const freq1 = grid[i][j]; - if (freq1 === '.') continue; // Skip empty spaces +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. - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - const freq2 = grid[k][l]; - if (freq2 !== freq1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies +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. - // Calculate the direction vector between the two antennas - const deltaX = k - i; - const deltaY = l - j; - const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY)); - const stepX = deltaX / gcd; - const stepY = deltaY / gcd; +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?",4766,"const fs = require('fs'); - // Calculate the two antinode positions - const antinode1 = { x: i - stepX, y: j - stepY }; - const antinode2 = { x: k + stepX, y: l + stepY }; +// Read and process input +const puzzleInput = fs.readFileSync('input.txt', 'utf-8').split(""\n""); - // Check if the antinodes are within the grid bounds - if (antinode1.x >= 0 && antinode1.x < rows && antinode1.y >= 0 && antinode1.y < cols) { - antinodeSet.add(`${antinode1.x},${antinode1.y}`); - } - if (antinode2.x >= 0 && antinode2.x < rows && antinode2.y >= 0 && antinode2.y < cols) { - antinodeSet.add(`${antinode2.x},${antinode2.y}`); - } - } - } - } - } +// Function to separate lines into rules and updates +const getRulesAndUpdates = (input) => { + const rules = []; + const updates = []; - return antinodeSet.size; + input.forEach((line) => { + if (line.includes('|')) rules.push(line); + else if (line.includes(',')) updates.push(line); + }); + + return { rules, updates }; }; -// Main function to calculate and log the result -const main = () => { - const antinodeCount = findAntinodes(grid); - console.log(antinodeCount); +// Function to check if an update satisfies a rule +const isValidUpdate = (update, rule) => { + const [rule1, rule2] = rule.split('|'); + if (update.includes(rule1) && update.includes(rule2)) { + const firstIndex = update.indexOf(rule1); + const secondIndex = update.indexOf(rule2); + return firstIndex < secondIndex; + } + return true; }; -// Execute the main function -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +// Function to find the middle page number from a valid update +const getMiddlePageNumber = (update) => update[Math.floor(update.length / 2)]; -You find yourselves on the roof of a top-secret Easter Bunny installation. +// Main logic to calculate the sum of middle page numbers +const calculateMiddlePageSum = (rules, updates) => { + return updates.reduce((sum, updateString) => { + const update = updateString.split(','); + const allValid = rules.every((rule) => isValidUpdate(update, rule)); -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + if (allValid) { + const middlePageNumber = getMiddlePageNumber(update); + sum += parseInt(middlePageNumber); + } -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + return sum; + }, 0); +}; -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +// Execution +const { rules, updates } = getRulesAndUpdates(puzzleInput); +const result = calculateMiddlePageSum(rules, updates); -So, for these two antennas with frequency a, they create the two antinodes marked with #: +console.log(result);",node:14 +2024,5,1,"--- Day 5: Print Queue --- -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +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. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +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. -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? +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. -Your puzzle answer was 332. +For example: ---- Part Two --- +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 -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +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.) -Whoops! +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. -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +To get the printers going as soon as possible, start by identifying which updates are already in the right order. -So, these three T-frequency antennas now create many antinodes: +In the above example, the first update (75,47,61,53,29) is in the right order: -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +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 original example now has 34 antinodes, including the antinodes that appear on every antenna: +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. -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); +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. -const grid = fs.readFileSync('input.txt', 'utf8').trim().split('\n').map(line => line.split('')); -const rows = grid.length; -const cols = grid[0].length; +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. -const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b); +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. -const findAntinodes = (grid) => { - const antinodeSet = new Set(); +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: - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const freq1 = grid[i][j]; - if (freq1 === '.') continue; +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. - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - const freq2 = grid[k][l]; - if (freq2 !== freq1 || (i === k && j === l)) continue; +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. - const deltaX = k - i; - const deltaY = l - j; - const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY)); - const stepX = deltaX / gcd; - const stepY = deltaY / gcd; +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?",4766,"const fs = require('fs'); + +// Read and process input +const puzzleInput = fs.readFileSync('input.txt', 'utf-8').split(""\n""); + +// Separate rules and updates from puzzle input +const [rules, updates] = puzzleInput.reduce(([rules, updates], line) => { + if (line.includes('|')) rules.push(line); + if (line.includes(',')) updates.push(line); + return [rules, updates]; +}, [[], []]); + +// Process updates and evaluate based on rules +const middlePageNumbers = updates + .map((updateString) => updateString.split(',')) + .filter((update) => { + return rules.every((ruleString) => { + const [rule1, rule2] = ruleString.split('|'); + if (update.includes(rule1) && update.includes(rule2)) { + const firstIndex = update.indexOf(rule1); + const secondIndex = update.indexOf(rule2); + return firstIndex < secondIndex; + } + return true; // Ignore the rule if it doesn't match + }); + }) + .map((update) => update[Math.floor(update.length / 2)]); - let x = i + stepX; - let y = j + stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodeSet.add(`${x},${y}`); - x += stepX; - y += stepY; - } +// Sum the middle page numbers +const result = middlePageNumbers.reduce((sum, number) => sum + parseInt(number), 0); - x = i - stepX; - y = j - stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodeSet.add(`${x},${y}`); - x -= stepX; - y -= stepY; - } - } - } - } - } +// Output the result +console.log(result);",node:14 +2024,5,1,"--- Day 5: Print Queue --- - return antinodeSet.size; -}; +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. -console.log(findAntinodes(grid));",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +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. -You find yourselves on the roof of a top-secret Easter Bunny installation. +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. -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +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. -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +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 -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +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.) -So, for these two antennas with frequency a, they create the two antinodes marked with #: +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. -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +To get the printers going as soon as possible, start by identifying which updates are already in the right order. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +In the above example, the first update (75,47,61,53,29) is in the right order: -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +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. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +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. -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? +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. -Your puzzle answer was 332. +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. ---- Part Two --- +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +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: -Whoops! +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. -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. -So, these three T-frequency antennas now create many antinodes: +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?",4766,"const fs = require('fs'); -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +// Function to read input and split by lines +const readInput = (filename) => fs.readFileSync(filename, 'utf-8').split(""\n""); -The original example now has 34 antinodes, including the antinodes that appear on every antenna: +// Function to separate rules and updates from the puzzle input +const separateRulesAndUpdates = (input) => { + const rules = []; + const updates = []; -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); + input.forEach(line => { + if (line.includes('|')) rules.push(line); + if (line.includes(',')) updates.push(line); + }); -// Load the grid from the input file -const loadGrid = (filePath) => { - return fs.readFileSync(filePath, 'utf8') - .trim() - .split('\n') - .map(row => row.split('')); + return { rules, updates }; }; -// Calculate the greatest common divisor (GCD) of two numbers -const gcd = (a, b) => { - while (b !== 0) [a, b] = [b, a % b]; - return a; +// Function to check if an update satisfies all the rules +const satisfiesRules = (update, rules) => { + return rules.every(ruleString => { + const [rule1, rule2] = ruleString.split('|'); + if (update.includes(rule1) && update.includes(rule2)) { + const firstIndex = update.indexOf(rule1); + const secondIndex = update.indexOf(rule2); + return firstIndex < secondIndex; + } + return true; + }); }; -// Find all unique antinode positions in the grid -const findAntinodes = (grid) => { - const rows = grid.length; - const cols = grid[0].length; - const antinodes = new Set(); +// Function to extract the middle page number from a valid update +const extractMiddlePageNumber = (update) => update[Math.floor(update.length / 2)]; - // Iterate through all pairs of antennas - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const freq = grid[i][j]; - if (freq === '.') continue; // Skip empty spaces +// Function to calculate the total of middle page numbers +const calculateTotal = (middlePageNumbers) => middlePageNumbers.reduce((sum, number) => sum + parseInt(number), 0); - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - if (grid[k][l] !== freq || (i === k && j === l)) continue; // Skip same antenna or different frequencies +// Main execution +const input = readInput('input.txt'); +const { rules, updates } = separateRulesAndUpdates(input); - // Calculate the direction vector - const dx = k - i; - const dy = l - j; - const divisor = gcd(Math.abs(dx), Math.abs(dy)); - const stepX = dx / divisor; - const stepY = dy / divisor; +const middlePageNumbers = updates + .map(updateString => updateString.split(',')) + .filter(update => satisfiesRules(update, rules)) + .map(extractMiddlePageNumber); - // Traverse in the direction of the vector - let x = i + stepX; - let y = j + stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodes.add(`${x},${y}`); - x += stepX; - y += stepY; - } +const result = calculateTotal(middlePageNumbers); - // Traverse in the opposite direction - x = i - stepX; - y = j - stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodes.add(`${x},${y}`); - x -= stepX; - y -= stepY; - } - } - } - } - } +console.log(result);",node:14 +2024,5,1,"--- Day 5: Print Queue --- - return antinodes.size; -}; +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. -// Main function to execute the solution -const main = () => { - const grid = loadGrid('input.txt'); - const result = findAntinodes(grid); - console.log(result); -}; +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. -// Run the program -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +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. -You find yourselves on the roof of a top-secret Easter Bunny installation. +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. -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +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. -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +For example: -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +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 -So, for these two antennas with frequency a, they create the two antinodes marked with #: +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.) -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +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: -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +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. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +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. -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. -Your puzzle answer was 332. +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. ---- Part Two --- +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: -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +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. -Whoops! +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +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?",4766,"let fs = require('fs'); +let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); -So, these three T-frequency antennas now create many antinodes: +let rules = []; +let updates = []; -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +puzzleInput.forEach((line) => { + if (line.includes('|')) rules.push(line); + if (line.includes(',')) updates.push(line); +}); -The original example now has 34 antinodes, including the antinodes that appear on every antenna: +let middlePageNumbers = []; -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); +updates.forEach((updateString) => { + let update = updateString.split(','); + let testResults = []; -// Helper function to compute the greatest common divisor (GCD) of two numbers -const computeGCD = (a, b) => { - while (b !== 0) { - [a, b] = [b, a % b]; - } - return Math.abs(a); -}; + rules.forEach((ruleString) => { + rule = ruleString.split('|'); -// Function to extract antennas from the input grid and organize them by frequency -const parseAntennas = (grid) => { - const antennas = {}; - - grid.forEach((line, y) => { - [...line].forEach((char, x) => { - if (/[a-zA-Z0-9]/.test(char)) { - if (!antennas[char]) { - antennas[char] = []; + if (update.includes(rule[0]) && update.includes(rule[1])) { + let firstIndex = update.indexOf(rule[0]); + let secondIndex = update.indexOf(rule[1]); + + if (firstIndex < secondIndex) { + testResults.push(true); + } else { + testResults.push(false); + } } - antennas[char].push({ x, y }); - } }); - }); - return antennas; -}; + if (!testResults.includes(false)) { + middlePageNumbers.push(update[Math.floor(update.length / 2)]); + } +}); -// Function to gather all unique antinode positions in the grid -const calculateAntinodes = (antennas, width, height) => { - const antinodes = new Set(); - - Object.entries(antennas).forEach(([freq, positions]) => { - const numPositions = positions.length; - - for (let i = 0; i < numPositions; i++) { - const first = positions[i]; +let result = 0; - for (let j = i + 1; j < numPositions; j++) { - const second = positions[j]; - let dx = second.x - first.x; - let dy = second.y - first.y; +middlePageNumbers.forEach((number) => { + result += parseInt(number); +}); - // Reduce the differences by the greatest common divisor (gcd) - const gcdValue = computeGCD(dx, dy); - dx /= gcdValue; - dy /= gcdValue; +console.log(result);",node:14 +2024,5,1,"--- Day 5: Print Queue --- - // Add antinodes along the line in both directions - addAntinodesAlongLine(first.x, first.y, dx, dy, width, height, antinodes); - addAntinodesAlongLine(first.x - dx, first.y - dy, -dx, -dy, width, height, antinodes); - } - } - }); +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. - return antinodes; -}; +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. -// Function to add antinode positions along a specific line direction -const addAntinodesAlongLine = (startX, startY, dx, dy, width, height, antinodes) => { - let x = startX; - let y = startY; +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. - // Add positions while moving along the line - while (x >= 0 && x < width && y >= 0 && y < height) { - const key = `${x},${y}`; - antinodes.add(key); - x += dx; - y += dy; - } -}; +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. -// Main execution function -const main = () => { - const input = fs.readFileSync('input.txt', 'utf8').trim(); - const grid = input.split('\n'); - const height = grid.length; - const width = grid[0].length; - - // Parse the antennas from the grid - const antennas = parseAntennas(grid); - - // Calculate all unique antinode positions - const antinodes = calculateAntinodes(antennas, width, height); - - // Output the number of unique antinodes - console.log(antinodes.size); -}; +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. -// Run the program -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +For example: -You find yourselves on the roof of a top-secret Easter Bunny installation. +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 -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +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.) -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +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. -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +To get the printers going as soon as possible, start by identifying which updates are already in the right order. -So, for these two antennas with frequency a, they create the two antinodes marked with #: +In the above example, the first update (75,47,61,53,29) is in the right order: -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +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: -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? +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. -Your puzzle answer was 332. +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. ---- Part Two --- +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?",4766,"const fs = require(""fs""); +const filename = ""input.txt""; -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +var buffer, rows; -Whoops! +try { + buffer = fs.readFileSync(__dirname + ""/"" + filename, ""utf8""); +} catch (e) { + throw e; +} -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +rows = buffer.toString().split(""\n""); -So, these three T-frequency antennas now create many antinodes: +var after_check_object = {}, flag = false, valid_instructions = 0; -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +for (let i = 0; i < rows.length - 1; i++) { + let row = rows[i]; -The original example now has 34 antinodes, including the antinodes that appear on every antenna: + if (row == """") { + flag = true; + continue; + } -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); + if (!flag) { + // Store rules + const [a, b] = row.split(""|""); + if (after_check_object[a] == undefined) { + after_check_object[a] = { + after: [b] + }; + } else { + if (!after_check_object[a].after.includes(b)) { + after_check_object[a].after.push(b); + } + } + } else { + let numbers = row.split("",""); + let valid_instruction = true; -// Load and parse the input file into a grid -const loadGrid = () => { - return fs.readFileSync('input.txt', 'utf8') - .trim() - .split('\n') - .map(line => line.split('')); -}; + for (let j = 0; j < rows.length - 1; j++) { + let number = numbers[j]; + let remainder_numbers = numbers.slice(j + 1); -// Compute the greatest common divisor (GCD) of two numbers -const calculateGCD = (a, b) => { - while (b !== 0) { - [a, b] = [b, a % b]; + for (let k = 0; k < remainder_numbers.length; k++) { + if (!after_check_object[number] || !after_check_object[number].after.includes(remainder_numbers[k])) { + valid_instruction = false; + break; + } + } + + if (valid_instruction === false) { + break; + } } - return a; -}; -// Find all unique antinode positions in the grid -const calculateAntinodes = (grid) => { - const rows = grid.length; - const cols = grid[0].length; - const antinodes = new Set(); + if (valid_instruction) { + // console.log(""Valid instruction list! "", { numbers, valid_instruction }); + valid_instructions += Number(numbers[Math.floor(numbers.length / 2)]); + } - // Iterate through all pairs of antennas - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const frequency = grid[i][j]; - if (frequency === '.') continue; // Skip empty spaces + } +} - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - if (grid[k][l] !== frequency || (i === k && j === l)) continue; // Skip same antenna or different frequencies +// console.table(rows); +// console.dir(after_check_object, { depth: null }); +console.log({ valid_instructions });",node:14 +2024,5,2,"--- Day 5: Print Queue --- - // Calculate the direction vector between the two antennas - const dx = k - i; - const dy = l - j; - const gcd = calculateGCD(Math.abs(dx), Math.abs(dy)); - const stepX = dx / gcd; - const stepY = dy / gcd; +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. - // Traverse in the direction of the vector to find antinodes - let x = i + stepX; - let y = j + stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodes.add(`${x},${y}`); - x += stepX; - y += stepY; - } +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. - // Traverse in the opposite direction to find antinodes - x = i - stepX; - y = j - stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodes.add(`${x},${y}`); - x -= stepX; - y -= stepY; - } - } - } - } - } +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. - return antinodes.size; -}; +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. -// Main function to execute the solution -const main = () => { - const grid = loadGrid(); - const antinodeCount = calculateAntinodes(grid); - console.log(antinodeCount); -}; +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. -// Run the main function -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +For example: -You find yourselves on the roof of a top-secret Easter Bunny installation. +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 -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +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.) -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +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. -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +To get the printers going as soon as possible, start by identifying which updates are already in the right order. -So, for these two antennas with frequency a, they create the two antinodes marked with #: +In the above example, the first update (75,47,61,53,29) is in the right order: -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +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. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. -Your puzzle answer was 332. +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 4766. --- Part Two --- -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. -Whoops! +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: -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +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. -So, these three T-frequency antennas now create many antinodes: +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?",6257,"const fs = require('fs'); -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +// Read the input file +const input = fs.readFileSync('input.txt', 'utf8'); +const lines = input.trim().split('\n'); -The original example now has 34 antinodes, including the antinodes that appear on every antenna: +let index = 0; +const rules = []; -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); +// Parse the rules +while (index < lines.length && lines[index].includes('|')) { + const [from, to] = lines[index].split('|').map(Number); + rules.push({ from, to }); + index++; +} -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const lines = input.split('\n'); -const height = lines.length; -const width = lines[0].length; -const antennas = {}; +// Skip blank lines +while (index < lines.length && lines[index].trim() === '') { + index++; +} -// Collect antennas by frequency -for (let y = 0; y < height; y++) { - const line = lines[y]; - for (let x = 0; x < width; x++) { - const char = line[x]; - if (/[a-zA-Z0-9]/.test(char)) { - if (!antennas[char]) antennas[char] = []; - antennas[char].push({ x, y }); +// Parse the updates +const updates = []; +for (; index < lines.length; index++) { + const line = lines[index].trim(); + if (line !== '') { + const pages = line.split(',').map(Number); + updates.push(pages); } - } } -const antinodes = new Set(); +// Function to check if an update is in correct order +function isCorrectOrder(update) { + const positions = new Map(); + update.forEach((page, idx) => positions.set(page, idx)); -function gcd(a, b) { - while (b !== 0) { - [a, b] = [b, a % b]; - } - return Math.abs(a); + for (const { from, to } of rules) { + if (positions.has(from) && positions.has(to)) { + if (positions.get(from) > positions.get(to)) return false; + } + } + return true; } -for (const freq in antennas) { - const positions = antennas[freq]; - const n = positions.length; - for (let i = 0; i < n; i++) { - const A = positions[i]; - for (let j = i + 1; j < n; j++) { - const B = positions[j]; - let dx = B.x - A.x; - let dy = B.y - A.y; - const stepGCD = gcd(dx, dy); - dx /= stepGCD; - dy /= stepGCD; +// Function to reorder an update according to the rules +function reorderUpdate(update) { + // Build a subgraph for the pages in the update + const pagesSet = new Set(update); + const graph = new Map(); + const inDegree = new Map(); + + // Initialize graph and in-degree + for (const page of pagesSet) { + graph.set(page, []); + inDegree.set(page, 0); + } - // Include positions along the line in both directions - const points = []; + // Add edges based on rules + for (const { from, to } of rules) { + if (pagesSet.has(from) && pagesSet.has(to)) { + graph.get(from).push(to); + inDegree.set(to, inDegree.get(to) + 1); + } + } - // From A towards B - let x = A.x; - let y = A.y; - while (x >= 0 && x < width && y >= 0 && y < height) { - const key = `${x},${y}`; - antinodes.add(key); - x += dx; - y += dy; - } + // Topological sort + const queue = []; + for (const [node, degree] of inDegree) { + if (degree === 0) queue.push(node); + } - // From A in the opposite direction - x = A.x - dx; - y = A.y - dy; - while (x >= 0 && x < width && y >= 0 && y < height) { - const key = `${x},${y}`; - antinodes.add(key); - x -= dx; - y -= dy; - } + const sorted = []; + while (queue.length > 0) { + const node = queue.shift(); + sorted.push(node); + for (const neighbor of graph.get(node)) { + inDegree.set(neighbor, inDegree.get(neighbor) - 1); + if (inDegree.get(neighbor) === 0) { + queue.push(neighbor); + } + } } - } + + // If sorting is not possible (cycle detected), return original update + if (sorted.length !== pagesSet.size) return update; + + return sorted; } -console.log(antinodes.size);",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +// Sum the middle page numbers after reordering incorrectly ordered updates +let sum = 0; +for (const update of updates) { + if (!isCorrectOrder(update)) { + const reordered = reorderUpdate(update); + const middleIndex = Math.floor(reordered.length / 2); + sum += reordered[middleIndex]; + } +} -You find yourselves on the roof of a top-secret Easter Bunny installation. +console.log(sum);",node:14 +2024,5,2,"--- Day 5: Print Queue --- -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +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. -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +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. -So, for these two antennas with frequency a, they create the two antinodes marked with #: +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. -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +For example: -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +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 -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +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.) -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +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. -// Read input file and split into lines -const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); +To get the printers going as soon as possible, start by identifying which updates are already in the right order. -// Parse the map into a grid of characters -const grid = input.map(line => line.split('')); +In the above example, the first update (75,47,61,53,29) is in the right order: -// Function to calculate the greatest common divisor (GCD) of two numbers -const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b)); +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. -// Function to calculate all unique antinode positions -const calculateAntinodes = (grid) => { - const antinodes = new Set(); - const rows = grid.length; - const cols = grid[0].length; +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. - // Iterate over all pairs of antennas - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const frequency1 = grid[i][j]; - if (frequency1 === '.') continue; // Skip empty spaces +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - const frequency2 = grid[k][l]; - if (frequency2 !== frequency1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies +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? - // Calculate the differences in positions - const dx = k - i; - const dy = l - j; +Your puzzle answer was 4766. - // Calculate the GCD to simplify the direction vector - const divisor = gcd(Math.abs(dx), Math.abs(dy)); - const stepX = dx / divisor; - const stepY = dy / divisor; +--- Part Two --- - // Calculate the two antinode positions - const antinode1X = i - stepX; - const antinode1Y = j - stepY; - const antinode2X = k + stepX; - const antinode2Y = l + stepY; +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. - // Check if the antinodes are within the grid bounds - if (antinode1X >= 0 && antinode1X < rows && antinode1Y >= 0 && antinode1Y < cols) { - antinodes.add(`${antinode1X},${antinode1Y}`); - } - if (antinode2X >= 0 && antinode2X < rows && antinode2Y >= 0 && antinode2Y < cols) { - antinodes.add(`${antinode2X},${antinode2Y}`); - } - } - } - } - } +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: - return antinodes.size; -}; +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. -// Calculate and print the number of unique antinode locations -console.log(calculateAntinodes(grid));",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +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?",6257,"let fs = require('fs'); +let puzzleInput = fs.readFileSync('input.txt').toString().split(""\n""); -You find yourselves on the roof of a top-secret Easter Bunny installation. +let rules = []; +let updates = []; -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +let checkRules = (update, rules) => { + let updateFixed = false; + let fails = 0; + rules.forEach((ruleString) => { + rule = ruleString.split('|'); -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + if (update.includes(rule[0]) && update.includes(rule[1])) { + let firstIndex = update.indexOf(rule[0]); + let secondIndex = update.indexOf(rule[1]); -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + if (firstIndex > secondIndex) { + fails++; + update[secondIndex] = rule[0]; + update[firstIndex] = rule[1]; + updateFixed = true; + } + } + }); -So, for these two antennas with frequency a, they create the two antinodes marked with #: + if (updateFixed && fails > 1) checkRules(update, rules); + if (updateFixed) return update; + return false; +} -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +puzzleInput.forEach((line) => { + if (line.includes('|')) rules.push(line); + if (line.includes(',')) updates.push(line); +}); -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +let fixedUpdates = []; -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +updates.forEach((updateString) => { + let update = updateString.split(','); + let fixedUpdate = checkRules(update, rules); + + if (fixedUpdate) fixedUpdates.push(fixedUpdate); +}); -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +let result = 0; -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +fixedUpdates.forEach((update) => result += parseInt(update[Math.floor(update.length / 2)])); -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const lines = input.split('\n'); -const height = lines.length; -const width = lines[0].length; -const antennas = {}; +console.log(result);",node:14 +2024,5,2,"--- Day 5: Print Queue --- -// Collect antennas by frequency -for (let y = 0; y < height; y++) { - const line = lines[y]; - for (let x = 0; x < width; x++) { - const char = line[x]; - if (/[a-zA-Z0-9]/.test(char)) { - if (!antennas[char]) antennas[char] = []; - antennas[char].push({ x, y }); - } - } -} +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. -const antinodes = new Set(); +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. -for (const freq in antennas) { - const positions = antennas[freq]; - const n = positions.length; - for (let i = 0; i < n; i++) { - const A = positions[i]; - for (let j = i + 1; j < n; j++) { - const B = positions[j]; - const dx = A.x - B.x; - const dy = A.y - B.y; - const D = { x: dx, y: dy }; +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. - // Antinodes occur at positions where one antenna is twice as far as the other - const tValues = [-1, 2]; +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. - for (const t of tValues) { - const Px = B.x + t * D.x; - const Py = B.y + t * D.y; - if ( - Number.isInteger(Px) && - Number.isInteger(Py) && - Px >= 0 && - Px < width && - Py >= 0 && - Py < height - ) { - const key = `${Px},${Py}`; - antinodes.add(key); - } - } - } - } -} +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. -console.log(antinodes.size);",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +For example: -You find yourselves on the roof of a top-secret Easter Bunny installation. +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 -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +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.) -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +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. -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +To get the printers going as soon as possible, start by identifying which updates are already in the right order. -So, for these two antennas with frequency a, they create the two antinodes marked with #: +In the above example, the first update (75,47,61,53,29) is in the right order: -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +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: -// Utility function to read and split input into lines -function getInput(filePath) { - return fs.readFileSync(filePath, 'utf8').trim().split('\n'); -} +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. -// Utility function to find antennas by frequency -function findAntennas(lines) { - const antennas = {}; +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. - lines.forEach((line, y) => { - Array.from(line).forEach((char, x) => { - if (/[a-zA-Z0-9]/.test(char)) { - antennas[char] = antennas[char] || []; - antennas[char].push({ x, y }); - } - }); - }); +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? - return antennas; -} +Your puzzle answer was 4766. -// Function to calculate antinodes from antenna pairs -function calculateAntinodes(antennas, width, height) { - const antinodes = new Set(); +--- Part Two --- - Object.keys(antennas).forEach((freq) => { - const positions = antennas[freq]; - const n = positions.length; +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. - for (let i = 0; i < n; i++) { - const A = positions[i]; - for (let j = i + 1; j < n; j++) { - const B = positions[j]; - const dx = A.x - B.x; - const dy = A.y - B.y; +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: - // Check antinode conditions for both t = -1 and t = 2 - [-1, 2].forEach((t) => { - const Px = B.x + t * dx; - const Py = B.y + t * dy; +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. - // Ensure that Px and Py are within bounds and valid positions - if (Number.isInteger(Px) && Number.isInteger(Py) && - Px >= 0 && Px < width && Py >= 0 && Py < height) { - const key = `${Px},${Py}`; - antinodes.add(key); - } - }); +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?",6257,"const fs = require(""fs""); +const inputText = ""./input.txt""; + +fs.readFile(inputText, ""utf8"", (err, data) => { + if (err) { + console.error('Error reading file:', err); + return; + } + + const [instructions, updates] = data + .split(""\n\n"") + .map(section => section + .split(""\n"") + .map(line => line.split(/[|,]/))); + const [validUpdates, invalidUpdates] = getValidInvalidUpdates(instructions, updates); + + console.log(part1(validUpdates)); + console.log(part2(instructions, invalidUpdates)); +}); + +const getValidInvalidUpdates = (instructions, updates) => { + const validUpdates = []; + const invalidUpdates = []; + + for (let update of updates) { + let valid = true; + for (let [first, second] of instructions) { + const firstIndex = update.indexOf(first); + const secondIndex = update.indexOf(second); + if (firstIndex !== -1 && secondIndex !== -1 && firstIndex > secondIndex) { + valid = false; + break; } } - }); + if (valid) { + validUpdates.push(update); + } else { + invalidUpdates.push(update); + } + } + return [validUpdates, invalidUpdates]; +} - return antinodes; +const part1 = validUpdates => { + return validUpdates.reduce((validMiddlePages, update) => + validMiddlePages + Number(update[Math.floor(update.length / 2)]) + , 0); } -// Main function to execute the solution -function solve(filePath) { - const lines = getInput(filePath); - const height = lines.length; - const width = lines[0].length; +const reorderUpdate = (update, instructions) => { + const sortedUpdate = [...update]; + let reordered = true; + + // If the update needs to be reordered, keep running it through the loop until it is fixed + while (reordered) { + reordered = false; + for (let [first, second] of instructions) { + const firstIndex = sortedUpdate.indexOf(first); + const secondIndex = sortedUpdate.indexOf(second); + + if (firstIndex !== -1 && secondIndex !== -1 && firstIndex > secondIndex) { + // Remove first num, reinsert it before second num + sortedUpdate.splice(firstIndex, 1); + sortedUpdate.splice(secondIndex, 0, first); + reordered = true; + } + } + } + return sortedUpdate; +}; - const antennas = findAntennas(lines); - const antinodes = calculateAntinodes(antennas, width, height); +const part2 = (instructions, invalidUpdates) => { + return invalidUpdates.reduce((reorderedMiddlePages, update) => { + const reorderedUpdate = reorderUpdate(update, instructions); + return reorderedMiddlePages + Number(reorderedUpdate[Math.floor(reorderedUpdate.length / 2)]); + }, 0); +}",node:14 +2024,5,2,"--- Day 5: Print Queue --- - console.log(antinodes.size); -} +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. -// Run the solution -solve('input.txt');",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +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. -You find yourselves on the roof of a top-secret Easter Bunny installation. +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. -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +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. -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +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. -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +For example: -So, for these two antennas with frequency a, they create the two antinodes marked with #: +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 -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +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.) -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +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. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +To get the printers going as soon as possible, start by identifying which updates are already in the right order. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +In the above example, the first update (75,47,61,53,29) is in the right order: -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +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. -// Read and parse the input file -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const mapLines = input.split('\n'); -const mapHeight = mapLines.length; -const mapWidth = mapLines[0].length; +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. -// Function to locate antennas by frequency in the map -function extractAntennas(mapLines) { - const antennas = {}; +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. - mapLines.forEach((line, y) => { - Array.from(line).forEach((char, x) => { - if (/[a-zA-Z0-9]/.test(char)) { - if (!antennas[char]) { - antennas[char] = []; - } - antennas[char].push({ x, y }); - } - }); - }); +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. - return antennas; -} +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. -// Function to calculate all antinode positions -function findAntinodePositions(antennas, mapWidth, mapHeight) { - const antinodes = new Set(); +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. - Object.entries(antennas).forEach(([freq, positions]) => { - for (let i = 0; i < positions.length; i++) { - const firstPos = positions[i]; - for (let j = i + 1; j < positions.length; j++) { - const secondPos = positions[j]; +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? - // Calculate the difference between the two positions - const dx = firstPos.x - secondPos.x; - const dy = firstPos.y - secondPos.y; +Your puzzle answer was 4766. - // Check for potential antinodes - [-1, 2].forEach(t => { - const Px = secondPos.x + t * dx; - const Py = secondPos.y + t * dy; +--- Part Two --- - // Check if the calculated position is within bounds - if (Px >= 0 && Px < mapWidth && Py >= 0 && Py < mapHeight && Number.isInteger(Px) && Number.isInteger(Py)) { - antinodes.add(`${Px},${Py}`); - } - }); - } - } - }); +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. - return antinodes; -} +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: -// Main execution function -function main() { - const antennas = extractAntennas(mapLines); - const antinodes = findAntinodePositions(antennas, mapWidth, mapHeight); - console.log(antinodes.size); -} +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. -main();",node:14 -2024,8,1,"--- Day 8: Resonant Collinearity --- +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?",6257,"const fs = require(""fs""); +const inputText = ""./input.txt""; -You find yourselves on the roof of a top-secret Easter Bunny installation. +// Read the input file asynchronously +fs.readFile(inputText, ""utf8"", (err, data) => { + if (err) { + console.error(""Error reading file:"", err); + return; + } -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + const [instructions, updates] = parseInputData(data); + const [validUpdates, invalidUpdates] = classifyUpdates(instructions, updates); -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + console.log(calculateValidUpdatesSum(validUpdates)); + console.log(calculateReorderedUpdatesSum(instructions, invalidUpdates)); +}); -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +// Function to parse input data into instructions and updates +const parseInputData = (data) => { + return data.split(""\n\n"").map(section => + section.split(""\n"").map(line => line.split(/[|,]/)) + ); +}; -So, for these two antennas with frequency a, they create the two antinodes marked with #: +// Function to classify updates into valid and invalid categories +const classifyUpdates = (instructions, updates) => { + const validUpdates = []; + const invalidUpdates = []; -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: + updates.forEach((update) => { + const isValid = checkUpdateValidity(update, instructions); + if (isValid) validUpdates.push(update); + else invalidUpdates.push(update); + }); -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: + return [validUpdates, invalidUpdates]; +}; -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +// Function to check if a given update is valid based on instructions +const checkUpdateValidity = (update, instructions) => { + for (let [first, second] of instructions) { + const firstIndex = update.indexOf(first); + const secondIndex = update.indexOf(second); + if (firstIndex !== -1 && secondIndex !== -1 && firstIndex > secondIndex) { + return false; + } + } + return true; +}; -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +// Function to calculate the sum of the middle pages from valid updates +const calculateValidUpdatesSum = (validUpdates) => { + return validUpdates.reduce((sum, update) => + sum + Number(update[Math.floor(update.length / 2)]), 0 + ); +}; -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode?",332,"const fs = require('fs'); +// Function to reorder updates based on instructions +const reorderUpdate = (update, instructions) => { + const sortedUpdate = [...update]; + let isReordered = true; + + // Keep reordering until no more changes are needed + while (isReordered) { + isReordered = false; + for (let [first, second] of instructions) { + const firstIndex = sortedUpdate.indexOf(first); + const secondIndex = sortedUpdate.indexOf(second); + + if (firstIndex !== -1 && secondIndex !== -1 && firstIndex > secondIndex) { + // Reorder the update by moving 'first' before 'second' + sortedUpdate.splice(firstIndex, 1); + sortedUpdate.splice(secondIndex, 0, first); + isReordered = true; + } + } + } + return sortedUpdate; +}; -// Read and parse the input file into a grid -const grid = fs.readFileSync('input.txt', 'utf8') - .trim() - .split('\n') - .map(line => line.split('')); +// Function to calculate the sum of the middle pages from reordered invalid updates +const calculateReorderedUpdatesSum = (instructions, invalidUpdates) => { + return invalidUpdates.reduce((sum, update) => { + const reorderedUpdate = reorderUpdate(update, instructions); + return sum + Number(reorderedUpdate[Math.floor(reorderedUpdate.length / 2)]); + }, 0); +};",node:14 +2024,5,2,"--- Day 5: Print Queue --- -// Helper function to compute the greatest common divisor (GCD) -const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b); +Satisfied with their search on Ceres, the squadron of scholars suggests subsequently scanning the stationery stacks of sub-basement 17. -// Function to find all unique antinode positions -const findAntinodes = (grid) => { - const rows = grid.length; - const cols = grid[0].length; - const antinodeSet = new Set(); +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. - // Iterate through all pairs of antennas - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const freq1 = grid[i][j]; - if (freq1 === '.') continue; // Skip empty spaces +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. - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - const freq2 = grid[k][l]; - if (freq2 !== freq1 || (i === k && j === l)) continue; // Skip same antenna or different frequencies +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. - // Calculate the direction vector between the two antennas - const deltaX = k - i; - const deltaY = l - j; - const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY)); - const stepX = deltaX / gcd; - const stepY = deltaY / gcd; +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. - // Calculate the two antinode positions - const antinode1 = { x: i - stepX, y: j - stepY }; - const antinode2 = { x: k + stepX, y: l + stepY }; +For example: - // Check if the antinodes are within the grid bounds - if (antinode1.x >= 0 && antinode1.x < rows && antinode1.y >= 0 && antinode1.y < cols) { - antinodeSet.add(`${antinode1.x},${antinode1.y}`); - } - if (antinode2.x >= 0 && antinode2.x < rows && antinode2.y >= 0 && antinode2.y < cols) { - antinodeSet.add(`${antinode2.x},${antinode2.y}`); - } - } - } - } - } +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 - return antinodeSet.size; -}; +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.) -// Main function to calculate and log the result -const main = () => { - const antinodeCount = findAntinodes(grid); - console.log(antinodeCount); -}; +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. -// Execute the main function -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +To get the printers going as soon as possible, start by identifying which updates are already in the right order. -You find yourselves on the roof of a top-secret Easter Bunny installation. +In the above example, the first update (75,47,61,53,29) is in the right order: -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +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. -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +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. -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +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. -So, for these two antennas with frequency a, they create the two antinodes marked with #: +The fifth update, 61,13,29, is also not in the correct order, since it breaks the rule 29|13. -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +The last update, 97,13,75,29,47, is not in the correct order due to breaking several rules. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +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: -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +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. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +Of course, you'll need to be careful: the actual list of page ordering rules is bigger and more complicated than the above example. -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? +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 332. +Your puzzle answer was 4766. --- Part Two --- -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +While the Elves get to work printing the correctly-ordered updates, you have a little time to fix the rest of them. -Whoops! +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: -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +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. -So, these three T-frequency antennas now create many antinodes: +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?",6257,"const fs = require('fs'); -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +// Read the input file and parse lines +const input = fs.readFileSync('input.txt', 'utf8').trim(); +const lines = input.split('\n'); -The original example now has 34 antinodes, including the antinodes that appear on every antenna: +// Function to parse rules from the input +const parseRules = (lines) => { + const rules = []; + let index = 0; -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); + while (index < lines.length && lines[index].includes('|')) { + const [from, to] = lines[index].split('|').map(Number); + rules.push({ from, to }); + index++; + } -// Helper function to compute the greatest common divisor (GCD) of two numbers -const computeGCD = (a, b) => { - while (b !== 0) { - [a, b] = [b, a % b]; + return { rules, nextIndex: index }; +}; + +// Function to parse updates from the input +const parseUpdates = (lines, startIndex) => { + const updates = []; + for (let index = startIndex; index < lines.length; index++) { + const line = lines[index].trim(); + if (line) { + const pages = line.split(',').map(Number); + updates.push(pages); + } } - return Math.abs(a); + return updates; }; -// Function to extract antennas from the input grid and organize them by frequency -const parseAntennas = (grid) => { - const antennas = {}; - - grid.forEach((line, y) => { - [...line].forEach((char, x) => { - if (/[a-zA-Z0-9]/.test(char)) { - if (!antennas[char]) { - antennas[char] = []; - } - antennas[char].push({ x, y }); - } - }); - }); +// Function to check if an update is in correct order +const isCorrectOrder = (update, rules) => { + const positions = new Map(); + update.forEach((page, idx) => positions.set(page, idx)); - return antennas; + return rules.every(({ from, to }) => { + if (positions.has(from) && positions.has(to)) { + return positions.get(from) < positions.get(to); + } + return true; + }); }; -// Function to gather all unique antinode positions in the grid -const calculateAntinodes = (antennas, width, height) => { - const antinodes = new Set(); - - Object.entries(antennas).forEach(([freq, positions]) => { - const numPositions = positions.length; - - for (let i = 0; i < numPositions; i++) { - const first = positions[i]; +// Function to reorder an update according to the rules using topological sort +const reorderUpdate = (update, rules) => { + const pagesSet = new Set(update); + const graph = new Map(); + const inDegree = new Map(); - for (let j = i + 1; j < numPositions; j++) { - const second = positions[j]; - let dx = second.x - first.x; - let dy = second.y - first.y; + // Initialize graph and in-degree + pagesSet.forEach(page => { + graph.set(page, []); + inDegree.set(page, 0); + }); - // Reduce the differences by the greatest common divisor (gcd) - const gcdValue = computeGCD(dx, dy); - dx /= gcdValue; - dy /= gcdValue; + // Add edges based on rules + rules.forEach(({ from, to }) => { + if (pagesSet.has(from) && pagesSet.has(to)) { + graph.get(from).push(to); + inDegree.set(to, inDegree.get(to) + 1); + } + }); - // Add antinodes along the line in both directions - addAntinodesAlongLine(first.x, first.y, dx, dy, width, height, antinodes); - addAntinodesAlongLine(first.x - dx, first.y - dy, -dx, -dy, width, height, antinodes); + // Topological sort + const queue = []; + inDegree.forEach((degree, node) => { + if (degree === 0) queue.push(node); + }); + + const sorted = []; + while (queue.length > 0) { + const node = queue.shift(); + sorted.push(node); + + for (const neighbor of graph.get(node)) { + inDegree.set(neighbor, inDegree.get(neighbor) - 1); + if (inDegree.get(neighbor) === 0) { + queue.push(neighbor); } } - }); + } - return antinodes; + // If sorting is not possible (cycle detected), return original update + return sorted.length === pagesSet.size ? sorted : update; }; -// Function to add antinode positions along a specific line direction -const addAntinodesAlongLine = (startX, startY, dx, dy, width, height, antinodes) => { - let x = startX; - let y = startY; +// Main logic +const { rules, nextIndex } = parseRules(lines); +const updates = parseUpdates(lines, nextIndex); - // Add positions while moving along the line - while (x >= 0 && x < width && y >= 0 && y < height) { - const key = `${x},${y}`; - antinodes.add(key); - x += dx; - y += dy; +// Calculate the sum of middle page numbers after reordering incorrectly ordered updates +const sum = updates.reduce((total, update) => { + if (!isCorrectOrder(update, rules)) { + const reordered = reorderUpdate(update, rules); + const middleIndex = Math.floor(reordered.length / 2); + total += reordered[middleIndex]; } -}; + return total; +}, 0); -// Main execution function -const main = () => { - const input = fs.readFileSync('input.txt', 'utf8').trim(); - const grid = input.split('\n'); - const height = grid.length; - const width = grid[0].length; - - // Parse the antennas from the grid - const antennas = parseAntennas(grid); - - // Calculate all unique antinode positions - const antinodes = calculateAntinodes(antennas, width, height); - - // Output the number of unique antinodes - console.log(antinodes.size); -}; +console.log(sum);",node:14 +2024,7,1,"--- Day 7: Bridge Repair --- -// Run the program -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? -You find yourselves on the roof of a top-secret Easter Bunny installation. +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +For example: -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. -So, for these two antennas with frequency a, they create the two antinodes marked with #: +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +Only three of the above equations can be made true by inserting operators: -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"const fs = require('fs'); + +// Read the input file, parse per line +const data = fs.readFileSync('input.txt', 'utf8'); +const lines = data.trim().split('\n'); + +let totalCalibration = 0; + +for (const line of lines) { + //Splits each line into the test value and a string of numbers. + //Parses the test value as an integer. + //Converts the list of number strings into an array of integers. + const [testValueStr, numbersStr] = line.split(':'); + const testValue = parseInt(testValueStr.trim()); + const numbers = numbersStr.trim().split(' ').map(Number); + + // Determines the total number of possible operator combinations (2^n), since each position can be either + or * + const n = numbers.length - 1; + const totalCombos = 1 << n; + let possible = false; + + // Loops through all possible combinations of + and *. + // Uses bit manipulation to decide which operator to use at each position. + // Evaluates the expression left to right according to the chosen operators. + // Checks if the result equals the test value + for (let i = 0; i < totalCombos; i++) { + let result = numbers[0]; + for (let j = 0; j < n; j++) { + const op = (i & (1 << j)) ? '+' : '*'; + if (op === '+') { + result += numbers[j + 1]; + } else { + result *= numbers[j + 1]; + } + } + if (result === testValue) { + possible = true; + break; + } + } + //Add the value to the total calibration + if (possible) { + totalCalibration += testValue; + } +} + +console.log(totalCalibration);",node:14 +2024,7,1,"--- Day 7: Bridge Repair --- -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. -Your puzzle answer was 332. +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). ---- Part Two --- +For example: -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. -Whoops! +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +Only three of the above equations can be made true by inserting operators: -So, these three T-frequency antennas now create many antinodes: +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"const fs = require('fs'); -The original example now has 34 antinodes, including the antinodes that appear on every antenna: +// Read the input file and parse the equations into an array of objects +const getEquations = (filePath) => { + return fs.readFileSync(filePath, 'utf8') + .trim() + .split('\n') + .map(line => { + const [testValue, numbers] = line.split(': '); + return { testValue: Number(testValue), numbers: numbers.split(' ').map(Number) }; + }); +}; -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); +// Helper function to evaluate an equation given an operator configuration +const evaluate = (numbers, operators) => { + return numbers.reduce((acc, num, idx) => { + if (idx === 0) return num; + const operator = operators[idx - 1]; + return operator === '+' ? acc + num : acc * num; + }); +}; -// Load and parse the input file into a grid -const loadGrid = () => { - return fs.readFileSync('input.txt', 'utf8') - .trim() - .split('\n') - .map(line => line.split('')); +// Helper function to generate all possible operator combinations for a given number of positions +const generateOperators = (count) => { + const result = []; + const operators = ['+', '*']; + + const totalCombinations = Math.pow(2, count); + for (let i = 0; i < totalCombinations; i++) { + result.push([...Array(count)].map((_, idx) => operators[(i >> idx) & 1])); + } + + return result; }; -// Compute the greatest common divisor (GCD) of two numbers -const calculateGCD = (a, b) => { - while (b !== 0) { - [a, b] = [b, a % b]; +// Function to check if an equation can be solved with any combination of operators +const isValidEquation = (testValue, numbers) => { + const operatorCombinations = generateOperators(numbers.length - 1); + + return operatorCombinations.some(operators => evaluate(numbers, operators) === testValue); +}; + +// Main function to calculate the total calibration result +const calculateTotalCalibration = (filePath) => { + const equations = getEquations(filePath); + let totalCalibration = 0; + + equations.forEach(({ testValue, numbers }) => { + if (isValidEquation(testValue, numbers)) { + totalCalibration += testValue; } - return a; + }); + + return totalCalibration; }; -// Find all unique antinode positions in the grid -const calculateAntinodes = (grid) => { - const rows = grid.length; - const cols = grid[0].length; - const antinodes = new Set(); +// Run the solution +console.log(`Total calibration result: ${calculateTotalCalibration('input.txt')}`);",node:14 +2024,7,1,"--- Day 7: Bridge Repair --- - // Iterate through all pairs of antennas - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const frequency = grid[i][j]; - if (frequency === '.') continue; // Skip empty spaces +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - if (grid[k][l] !== frequency || (i === k && j === l)) continue; // Skip same antenna or different frequencies +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. - // Calculate the direction vector between the two antennas - const dx = k - i; - const dy = l - j; - const gcd = calculateGCD(Math.abs(dx), Math.abs(dy)); - const stepX = dx / gcd; - const stepY = dy / gcd; +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). - // Traverse in the direction of the vector to find antinodes - let x = i + stepX; - let y = j + stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodes.add(`${x},${y}`); - x += stepX; - y += stepY; - } +For example: - // Traverse in the opposite direction to find antinodes - x = i - stepX; - y = j - stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodes.add(`${x},${y}`); - x -= stepX; - y -= stepY; - } - } - } - } +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"const fs = require('fs'); + +// Read input from file and parse it +const loadInput = (filePath) => { + const input = fs.readFileSync(filePath, 'utf8').trim().split('\n'); + return input.map(line => { + const [testValue, numbers] = line.split(': '); + return { testValue: parseInt(testValue), numbers: numbers.split(' ').map(Number) }; + }); +}; + +// Perform the left-to-right evaluation for a given sequence of numbers and operators +const evaluateExpression = (numbers, operators) => { + return numbers.reduce((result, num, index) => { + if (index === 0) return num; + const operator = operators[index - 1]; + return operator === '+' ? result + num : result * num; + }, 0); +}; + +// Generate all combinations of operators for the given numbers +const generateOperatorCombinations = (length) => { + const ops = ['+', '*']; + const combinations = []; + const totalCombinations = Math.pow(2, length); + + for (let i = 0; i < totalCombinations; i++) { + const combination = []; + for (let j = 0; j < length; j++) { + combination.push(ops[(i >> j) & 1]); } + combinations.push(combination); + } - return antinodes.size; + return combinations; }; -// Main function to execute the solution -const main = () => { - const grid = loadGrid(); - const antinodeCount = calculateAntinodes(grid); - console.log(antinodeCount); +// Check if a given test value can be achieved with the numbers and operators +const isValidEquation = (testValue, numbers) => { + const operatorCombinations = generateOperatorCombinations(numbers.length - 1); + return operatorCombinations.some(operators => evaluateExpression(numbers, operators) === testValue); }; -// Run the main function -main();",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +// Main function to calculate the total sum of valid test values +const calculateTotalCalibration = (filePath) => { + const equations = loadInput(filePath); + return equations.reduce((sum, { testValue, numbers }) => { + if (isValidEquation(testValue, numbers)) { + return sum + testValue; + } + return sum; + }, 0); +}; -You find yourselves on the roof of a top-secret Easter Bunny installation. +// Call the main function and print the result +const result = calculateTotalCalibration('input.txt'); +console.log(result);",node:14 +2024,7,1,"--- Day 7: Bridge Repair --- -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). -So, for these two antennas with frequency a, they create the two antinodes marked with #: +For example: -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"const fs = require('fs'); + +// Read the file and return the equations as an array of objects +const parseInput = (path) => { + const data = fs.readFileSync(path, 'utf8').trim().split('\n'); + return data.map(line => { + const [test, nums] = line.split(': '); + return { testValue: +test, numbers: nums.split(' ').map(Number) }; + }); +}; + +// Evaluate a single expression with a list of operators applied left-to-right +const calcExpression = (nums, ops) => { + return nums.reduce((result, num, i) => { + if (i === 0) return num; + const op = ops[i - 1]; + return op === '+' ? result + num : result * num; + }, 0); +}; -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +// Generate all possible combinations of operators for a given number of positions +const getOperatorCombinations = (n) => { + const ops = ['+', '*']; + const combinations = []; -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? + for (let i = 0; i < Math.pow(2, n); i++) { + combinations.push([...Array(n)].map((_, j) => ops[(i >> j) & 1])); + } -Your puzzle answer was 332. + return combinations; +}; ---- Part Two --- +// Check if any combination of operators can satisfy the equation +const checkValidEquation = (testValue, numbers) => { + const operatorCombinations = getOperatorCombinations(numbers.length - 1); + return operatorCombinations.some(operators => calcExpression(numbers, operators) === testValue); +}; -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +// Solve the challenge by summing up all valid test values +const solveChallenge = (path) => { + const equations = parseInput(path); + return equations.reduce((sum, { testValue, numbers }) => { + return checkValidEquation(testValue, numbers) ? sum + testValue : sum; + }, 0); +}; -Whoops! +// Run the solution +const result = solveChallenge('input.txt'); +console.log(result);",node:14 +2024,7,1,"--- Day 7: Bridge Repair --- -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? -So, these three T-frequency antennas now create many antinodes: +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). -The original example now has 34 antinodes, including the antinodes that appear on every antenna: +For example: -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. -const grid = fs.readFileSync('input.txt', 'utf8').trim().split('\n').map(line => line.split('')); -const rows = grid.length; -const cols = grid[0].length; +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). -const computeGCD = (a, b) => b === 0 ? a : computeGCD(b, a % b); +Only three of the above equations can be made true by inserting operators: -const findAntinodes = (grid) => { - const antinodeSet = new Set(); +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const freq1 = grid[i][j]; - if (freq1 === '.') continue; +Determine which equations could possibly be true. What is their total calibration result?",1298103531759,"const fs = require('fs'); - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - const freq2 = grid[k][l]; - if (freq2 !== freq1 || (i === k && j === l)) continue; +// Read the input file and parse the equations +const readInput = (filePath) => { + return fs.readFileSync(filePath, 'utf8').trim().split('\n').map(line => { + const [testValue, numbers] = line.split(': '); + return { testValue: Number(testValue), numbers: numbers.split(' ').map(Number) }; + }); +}; - const deltaX = k - i; - const deltaY = l - j; - const gcd = computeGCD(Math.abs(deltaX), Math.abs(deltaY)); - const stepX = deltaX / gcd; - const stepY = deltaY / gcd; +// Function to evaluate an expression with a given operator configuration +const evaluateExpression = (numbers, operators) => { + let result = numbers[0]; + for (let i = 0; i < operators.length; i++) { + if (operators[i] === '+') { + result += numbers[i + 1]; + } else if (operators[i] === '*') { + result *= numbers[i + 1]; + } + } + return result; +}; - let x = i + stepX; - let y = j + stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodeSet.add(`${x},${y}`); - x += stepX; - y += stepY; - } +// Function to generate all possible operator combinations +const generateOperatorCombinations = (length) => { + const combinations = []; + const operators = ['+', '*']; + const totalCombinations = Math.pow(2, length); - x = i - stepX; - y = j - stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodeSet.add(`${x},${y}`); - x -= stepX; - y -= stepY; - } - } - } - } + for (let i = 0; i < totalCombinations; i++) { + let combo = []; + for (let j = 0; j < length; j++) { + combo.push(operators[(i >> j) & 1]); } + combinations.push(combo); + } - return antinodeSet.size; + return combinations; }; -console.log(findAntinodes(grid));",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +// Function to check if the equation is valid for a given set of numbers and operators +const isValidEquation = (testValue, numbers) => { + const operatorCombinations = generateOperatorCombinations(numbers.length - 1); -You find yourselves on the roof of a top-secret Easter Bunny installation. + for (let combo of operatorCombinations) { + const result = evaluateExpression(numbers, combo); + if (result === testValue) { + return true; + } + } -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! + return false; +}; -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: +// Main function to solve the problem +const solve = (filePath) => { + const equations = readInput(filePath); + let totalCalibration = 0; -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. + for (const { testValue, numbers } of equations) { + if (isValidEquation(testValue, numbers)) { + totalCalibration += testValue; + } + } -So, for these two antennas with frequency a, they create the two antinodes marked with #: + console.log(`Total calibration result: ${totalCalibration}`); +}; -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +// Run the solution +solve('input.txt');",node:14 +2024,7,2,"--- Day 7: Bridge Repair --- -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? +For example: -Your puzzle answer was 332. +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. + +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). + +Only three of the above equations can be made true by inserting operators: + +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. + +Determine which equations could possibly be true. What is their total calibration result? + +Your puzzle answer was 1298103531759. --- Part Two --- -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. + +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. + +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: + +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. + +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"const fs = require('fs'); + +const input = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); + +const evaluate = (nums, ops) => { + let result = nums[0]; + for (let i = 0; i < ops.length; i++) { + if (ops[i] === '+') { + result += nums[i + 1]; + } else if (ops[i] === '*') { + result *= nums[i + 1]; + } else if (ops[i] === '||') { + result = parseInt(`${result}${nums[i + 1]}`, 10); + } + } + return result; +}; + +const solve = (line) => { + const [target, numsStr] = line.split(':'); + const nums = numsStr.trim().split(' ').map(Number); + const n = nums.length; + const operators = ['+', '*', '||']; + const stack = [{ nums, ops: [] }]; + + while (stack.length > 0) { + const { nums, ops } = stack.pop(); + if (ops.length === n - 1) { + if (evaluate(nums, ops) === parseInt(target, 10)) { + return parseInt(target, 10); + } + } else { + for (const op of operators) { + stack.push({ nums, ops: [...ops, op] }); + } + } + } + return 0; +}; + +let total = 0; +for (const line of input) { + total += solve(line); +} +console.log(total);",node:14 +2024,7,2,"--- Day 7: Bridge Repair --- + +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? -Whoops! +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). -So, these three T-frequency antennas now create many antinodes: +For example: -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. -The original example now has 34 antinodes, including the antinodes that appear on every antenna: +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); +Only three of the above equations can be made true by inserting operators: -const input = fs.readFileSync('input.txt', 'utf8').trim(); -const lines = input.split('\n'); -const height = lines.length; -const width = lines[0].length; -const antennas = {}; +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. -// Collect antennas by frequency -for (let y = 0; y < height; y++) { - const line = lines[y]; - for (let x = 0; x < width; x++) { - const char = line[x]; - if (/[a-zA-Z0-9]/.test(char)) { - if (!antennas[char]) antennas[char] = []; - antennas[char].push({ x, y }); - } - } -} +Determine which equations could possibly be true. What is their total calibration result? -const antinodes = new Set(); +Your puzzle answer was 1298103531759. -function gcd(a, b) { - while (b !== 0) { - [a, b] = [b, a % b]; - } - return Math.abs(a); -} +--- Part Two --- -for (const freq in antennas) { - const positions = antennas[freq]; - const n = positions.length; - for (let i = 0; i < n; i++) { - const A = positions[i]; - for (let j = i + 1; j < n; j++) { - const B = positions[j]; - let dx = B.x - A.x; - let dy = B.y - A.y; - const stepGCD = gcd(dx, dy); - dx /= stepGCD; - dy /= stepGCD; +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. - // Include positions along the line in both directions - const points = []; +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. - // From A towards B - let x = A.x; - let y = A.y; - while (x >= 0 && x < width && y >= 0 && y < height) { - const key = `${x},${y}`; - antinodes.add(key); - x += dx; - y += dy; - } +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: - // From A in the opposite direction - x = A.x - dx; - y = A.y - dy; - while (x >= 0 && x < width && y >= 0 && y < height) { - const key = `${x},${y}`; - antinodes.add(key); - x -= dx; - y -= dy; - } - } - } -} +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. -console.log(antinodes.size);",node:14 -2024,8,2,"--- Day 8: Resonant Collinearity --- +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"const fs = require('fs'); -You find yourselves on the roof of a top-secret Easter Bunny installation. +// Read the input file and convert it into an array of equations with test values and numbers +const parseInputFile = (filePath) => { + const inputData = fs.readFileSync(filePath, 'utf8').trim().split('\n'); + return inputData.map(line => { + const [testValue, numbers] = line.split(': '); + return { + testValue: Number(testValue), + numbers: numbers.split(' ').map(Number) + }; + }); +}; -While The Historians do their thing, you take a look at the familiar huge antenna. Much to your surprise, it seems to have been reconfigured to emit a signal that makes people 0.1% more likely to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift! Unthinkable! +// Generate all possible operator combinations (+, *, ||) for a given length of numbers +const generateOperatorCombinations = (length) => { + const operators = ['+', '*', '||']; + const totalCombinations = Math.pow(3, length); + const combinations = []; -Scanning across the city, you find that there are actually many such antennas. Each antenna is tuned to a specific frequency indicated by a single lowercase letter, uppercase letter, or digit. You create a map (your puzzle input) of these antennas. For example: + for (let i = 0; i < totalCombinations; i++) { + const combo = []; + for (let j = 0; j < length; j++) { + combo.push(operators[(i / Math.pow(3, j)) % 3 | 0]); + } + combinations.push(combo); + } + return combinations; +}; -............ -........0... -.....0...... -.......0.... -....0....... -......A..... -............ -............ -........A... -.........A.. -............ -............ -The signal only applies its nefarious effect at specific antinodes based on the resonant frequencies of the antennas. In particular, an antinode occurs at any point that is perfectly in line with two antennas of the same frequency - but only when one of the antennas is twice as far away as the other. This means that for any pair of antennas with the same frequency, there are two antinodes, one on either side of them. +// Function to concatenate two numbers when using the '||' operator +const concatenateNumbers = (num1, num2) => { + return parseInt(num1.toString() + num2.toString()); +}; -So, for these two antennas with frequency a, they create the two antinodes marked with #: +// Evaluate the expression considering all the operators (+, *, ||) between the numbers +const evaluateWithOperators = (numbers, operators) => { + return numbers.reduce((accum, num, index) => { + if (index === 0) return num; + const operator = operators[index - 1]; + if (operator === '+') return accum + num; + if (operator === '*') return accum * num; + if (operator === '||') return concatenateNumbers(accum, num); + return accum; + }, 0); +}; -.......... -...#...... -.......... -....a..... -.......... -.....a.... -.......... -......#... -.......... -.......... -Adding a third antenna with the same frequency creates several more antinodes. It would ideally add four antinodes, but two are off the right side of the map, so instead it adds only two: +// Check if a given equation is valid by evaluating it with all possible operator combinations +const isEquationValid = (testValue, numbers) => { + const operatorCombinations = generateOperatorCombinations(numbers.length - 1); + return operatorCombinations.some(operators => { + return evaluateWithOperators(numbers, operators) === testValue; + }); +}; -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......#... -.......... -.......... -Antennas with different frequencies don't create antinodes; A and a count as different frequencies. However, antinodes can occur at locations that contain antennas. In this diagram, the lone antenna with frequency capital A creates no antinodes but has a lowercase-a-frequency antinode at its location: +// Sum up the test values of all valid equations +const calculateCalibrationResult = (filePath) => { + const equations = parseInputFile(filePath); + let totalResult = 0; -.......... -...#...... -#......... -....a..... -........a. -.....a.... -..#....... -......A... -.......... -.......... -The first example has antennas with two different frequencies, so the antinodes they create look like this, plus an antinode overlapping the topmost A-frequency antenna: + equations.forEach(({ testValue, numbers }) => { + if (isEquationValid(testValue, numbers)) { + totalResult += testValue; + } + }); -......#....# -...#....0... -....#0....#. -..#....0.... -....0....#.. -.#....A..... -...#........ -#......#.... -........A... -.........A.. -..........#. -..........#. -Because the topmost A-frequency antenna overlaps with a 0-frequency antinode, there are 14 total unique locations that contain an antinode within the bounds of the map. + return totalResult; +}; -Calculate the impact of the signal. How many unique locations within the bounds of the map contain an antinode? +// Output the total calibration result +const calibrationResult = calculateCalibrationResult('input.txt'); +console.log(calibrationResult);",node:14 +2024,7,2,"--- Day 7: Bridge Repair --- -Your puzzle answer was 332. +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? ---- Part Two --- +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. -Watching over your shoulder as you work, one of The Historians asks if you took the effects of resonant harmonics into your calculations. +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). -Whoops! +For example: -After updating your model, it turns out that an antinode occurs at any grid position exactly in line with at least two antennas of the same frequency, regardless of distance. This means that some of the new antinodes will occur at the position of each antenna (unless that antenna is the only one of its frequency). +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. -So, these three T-frequency antennas now create many antinodes: +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). -T....#.... -...T...... -.T....#... -.........# -..#....... -.......... -...#...... -.......... -....#..... -.......... -In fact, the three T-frequency antennas are all exactly in line with two antennas, so they are all also antinodes! This brings the total number of antinodes in the above example to 9. +Only three of the above equations can be made true by inserting operators: -The original example now has 34 antinodes, including the antinodes that appear on every antenna: +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. -##....#....# -.#.#....0... -..#.#0....#. -..##...0.... -....0....#.. -.#...#A....# -...#..#..... -#....#.#.... -..#.....A... -....#....A.. -.#........#. -...#......## -Calculate the impact of the signal using this updated model. How many unique locations within the bounds of the map contain an antinode?",1174,"const fs = require('fs'); +Determine which equations could possibly be true. What is their total calibration result? -// Load the grid from the input file -const loadGrid = (filePath) => { - return fs.readFileSync(filePath, 'utf8') - .trim() - .split('\n') - .map(row => row.split('')); -}; +Your puzzle answer was 1298103531759. -// Calculate the greatest common divisor (GCD) of two numbers -const gcd = (a, b) => { - while (b !== 0) [a, b] = [b, a % b]; - return a; -}; +--- Part Two --- -// Find all unique antinode positions in the grid -const findAntinodes = (grid) => { - const rows = grid.length; - const cols = grid[0].length; - const antinodes = new Set(); +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. - // Iterate through all pairs of antennas - for (let i = 0; i < rows; i++) { - for (let j = 0; j < cols; j++) { - const freq = grid[i][j]; - if (freq === '.') continue; // Skip empty spaces +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. - for (let k = 0; k < rows; k++) { - for (let l = 0; l < cols; l++) { - if (grid[k][l] !== freq || (i === k && j === l)) continue; // Skip same antenna or different frequencies +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: - // Calculate the direction vector - const dx = k - i; - const dy = l - j; - const divisor = gcd(Math.abs(dx), Math.abs(dy)); - const stepX = dx / divisor; - const stepY = dy / divisor; +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. - // Traverse in the direction of the vector - let x = i + stepX; - let y = j + stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodes.add(`${x},${y}`); - x += stepX; - y += stepY; - } +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"const fs = require('fs'); - // Traverse in the opposite direction - x = i - stepX; - y = j - stepY; - while (x >= 0 && x < rows && y >= 0 && y < cols) { - antinodes.add(`${x},${y}`); - x -= stepX; - y -= stepY; - } - } +// Read the input file +const data = fs.readFileSync('input.txt', 'utf8'); +const lines = data.trim().split('\n'); + +let totalCalibration = 0; + +for (const line of lines) { + const [testValueStr, numbersStr] = line.split(':'); + const testValue = parseInt(testValueStr.trim()); + const numbers = numbersStr.trim().split(' ').map(Number); + + const n = numbers.length - 1; + const totalCombos = Math.pow(3, n); + let possible = false; + + for (let i = 0; i < totalCombos; i++) { + let result = numbers[0]; + let combo = i; + for (let j = 0; j < n; j++) { + const opCode = combo % 3; + combo = Math.floor(combo / 3); + const num = numbers[j + 1]; + + if (opCode === 0) { + // Addition + result += num; + } else if (opCode === 1) { + // Multiplication + result *= num; + } else { + // Concatenation + result = parseInt('' + result + num); } } + if (result === testValue) { + possible = true; + break; + } } - return antinodes.size; -}; + if (possible) { + totalCalibration += testValue; + } +} -// Main function to execute the solution -const main = () => { - const grid = loadGrid('input.txt'); - const result = findAntinodes(grid); - console.log(result); -}; +console.log(totalCalibration);",node:14 +2024,7,2,"--- Day 7: Bridge Repair --- -// Run the program -main();",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). -He shows you the disk map (your puzzle input) he's already generated. For example: +For example: -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: +Only three of the above equations can be made true by inserting operators: -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +Determine which equations could possibly be true. What is their total calibration result? -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +Your puzzle answer was 1298103531759. -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +--- Part Two --- -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"const fs = require('fs'); +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. -// Load the disk map from the input file -const loadDiskMap = (filePath) => { - return fs.readFileSync(filePath, 'utf8').trim(); +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: + +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. + +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"const fs = require('fs'); + +// Read input file and split into lines +const lines = fs.readFileSync('input.txt', 'utf8').trim().split('\n'); + +// Function to evaluate a sequence of numbers with given operators +const evaluateExpression = (numbers, operators) => { + let result = numbers[0]; + for (let i = 0; i < operators.length; i++) { + const operator = operators[i]; + const nextNumber = numbers[i + 1]; + + if (operator === '+') { + result += nextNumber; + } else if (operator === '*') { + result *= nextNumber; + } else if (operator === '||') { + result = parseInt(`${result}${nextNumber}`, 10); + } + } + return result; }; -// Parse the disk map into a list of blocks -const parseDiskMap = (diskMap) => { - const blocks = []; - let isFile = true; - let fileId = 0; +// Function to check if a given equation can be solved with operators +const canSolveEquation = (target, numbers) => { + const operatorOptions = ['+', '*', '||']; + const stack = [{ numbers, operators: [] }]; - for (const char of diskMap) { - const length = parseInt(char, 10); - if (isFile) { - // Add file blocks with the current file ID - for (let i = 0; i < length; i++) { - blocks.push(fileId); + while (stack.length > 0) { + const { numbers, operators } = stack.pop(); + + // If all operators are placed, evaluate the expression + if (operators.length === numbers.length - 1) { + if (evaluateExpression(numbers, operators) === target) { + return true; } - fileId++; } else { - // Add free space blocks represented by -1 - for (let i = 0; i < length; i++) { - blocks.push(-1); + // Try adding each operator to the stack + for (const op of operatorOptions) { + stack.push({ numbers, operators: [...operators, op] }); } } - // Alternate between file and free space - isFile = !isFile; } - - return blocks; + return false; }; -// Compact the disk by moving file blocks to the leftmost free space -const compactDisk = (blocks) => { - while (true) { - const leftmostFreeIndex = blocks.indexOf(-1); - if (leftmostFreeIndex === -1) break; // No free space left - - let lastFileIndex = blocks.length - 1; - while (lastFileIndex > leftmostFreeIndex && blocks[lastFileIndex] === -1) { - lastFileIndex--; - } +// Main function to process all equations and calculate the total calibration result +const calculateCalibrationResult = (lines) => { + let total = 0; - if (lastFileIndex <= leftmostFreeIndex) break; // No file blocks to move + for (const line of lines) { + const [targetStr, numbersStr] = line.split(':'); + const target = parseInt(targetStr, 10); + const numbers = numbersStr.trim().split(' ').map(Number); - // Move the last file block to the leftmost free space - blocks[leftmostFreeIndex] = blocks[lastFileIndex]; - blocks[lastFileIndex] = -1; + if (canSolveEquation(target, numbers)) { + total += target; + } } - return blocks; + return total; }; -// Calculate the filesystem checksum -const calculateChecksum = (blocks) => { - return blocks.reduce((sum, block, index) => { - return block !== -1 ? sum + index * block : sum; - }, 0); -}; +// Output the total calibration result +console.log(calculateCalibrationResult(lines));",node:14 +2024,7,2,"--- Day 7: Bridge Repair --- -// Main function to execute the solution -const main = () => { - const diskMap = loadDiskMap('input.txt'); - const blocks = parseDiskMap(diskMap); - const compactedBlocks = compactDisk(blocks); - const checksum = calculateChecksum(compactedBlocks); - console.log(checksum); -}; +The Historians take you to a familiar rope bridge over a river in the middle of a jungle. The Chief isn't on this side of the bridge, though; maybe he's on the other side? -// Run the program -main();",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +When you go to cross the bridge, you notice a group of engineers trying to repair it. (Apparently, it breaks pretty frequently.) You won't be able to cross until it's fixed. -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. +You ask how long it'll take; the engineers tell you that it only needs final calibrations, but some young elephants were playing nearby and stole all the operators from their calibration equations! They could finish the calibrations if only someone could determine which test values could possibly be produced by placing any combination of operators into their calibration equations (your puzzle input). -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +For example: -He shows you the disk map (your puzzle input) he's already generated. For example: +190: 10 19 +3267: 81 40 27 +83: 17 5 +156: 15 6 +7290: 6 8 6 15 +161011: 16 10 13 +192: 17 8 14 +21037: 9 7 18 13 +292: 11 6 16 20 +Each line represents a single equation. The test value appears before the colon on each line; it is your job to determine whether the remaining numbers can be combined with operators to produce the test value. -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. +Operators are always evaluated left-to-right, not according to precedence rules. Furthermore, numbers in the equations cannot be rearranged. Glancing into the jungle, you can see elephants holding two different types of operators: add (+) and multiply (*). -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). +Only three of the above equations can be made true by inserting operators: -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: +190: 10 19 has only one position that accepts an operator: between 10 and 19. Choosing + would give 29, but choosing * would give the test value (10 * 19 = 190). +3267: 81 40 27 has two positions for operators. Of the four possible configurations of the operators, two cause the right side to match the test value: 81 + 40 * 27 and 81 * 40 + 27 both equal 3267 (when evaluated left-to-right)! +292: 11 6 16 20 can be solved in exactly one way: 11 + 6 * 16 + 20. +The engineers just need the total calibration result, which is the sum of the test values from just the equations that could possibly be true. In the above example, the sum of the test values for the three equations listed above is 3749. -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +Determine which equations could possibly be true. What is their total calibration result? -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +Your puzzle answer was 1298103531759. -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +--- Part Two --- -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +The engineers seem concerned; the total calibration result you gave them is nowhere close to being within safety tolerances. Just then, you spot your mistake: some well-hidden elephants are holding a third type of operator. + +The concatenation operator (||) combines the digits from its left and right inputs into a single number. For example, 12 || 345 would become 12345. All operators are still evaluated left-to-right. -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +Now, apart from the three equations that could be made true using only addition and multiplication, the above example has three more equations that can be made true by inserting operators: -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"const fs = require('fs'); +156: 15 6 can be made true through a single concatenation: 15 || 6 = 156. +7290: 6 8 6 15 can be made true using 6 * 8 || 6 * 15. +192: 17 8 14 can be made true using 17 || 8 + 14. +Adding up all six test values (the three that could be made before using only + and * plus the new three that can now be made by also using ||) produces the new total calibration result of 11387. -// Helper function to parse the input disk map into an array of file lengths and free space lengths -const parseDiskMap = (input) => { - const diskLengths = input.split('').map(Number); - let disk = []; - let fileId = 0; - let isFile = true; +Using your new knowledge of elephant hiding spots, determine which equations could possibly be true. What is their total calibration result?",140575048428831,"const fs = require('fs'); - // Build the initial disk representation by alternating between file blocks and free space blocks - diskLengths.forEach((length) => { - if (isFile) { - // Add file blocks - disk.push(...Array(length).fill(fileId)); - fileId++; - } else { - // Add free space blocks represented by -1 - disk.push(...Array(length).fill(-1)); - } - isFile = !isFile; // Toggle between file and free space - }); +// Read input file and parse it into an array of equations +const readInput = (filePath) => { + const data = fs.readFileSync(filePath, 'utf8').trim().split('\n'); + return data.map(line => { + const [testValue, numbers] = line.split(': '); + return { + testValue: parseInt(testValue), + numbers: numbers.split(' ').map(Number) + }; + }); +}; - return disk; +// Function to evaluate an expression with given numbers and operators +const evaluateExpression = (numbers, operators) => { + return numbers.reduce((result, num, index) => { + if (index === 0) return num; + const operator = operators[index - 1]; + if (operator === '+') return result + num; + if (operator === '*') return result * num; + return result; + }, 0); }; -// Helper function to simulate the compaction of files on the disk -const compactDisk = (disk) => { - let moved = true; +// Generate all possible combinations of operators (+, *, ||) for the numbers +const generateOperatorCombinations = (length) => { + const ops = ['+', '*', '||']; + const combinations = []; + const totalCombinations = Math.pow(3, length); - while (moved) { - moved = false; - - // Find the leftmost free space index - let leftmostFreeIndex = disk.indexOf(-1); - if (leftmostFreeIndex === -1) { - // No free space left, disk is compacted - break; - } + for (let i = 0; i < totalCombinations; i++) { + const combination = []; + for (let j = 0; j < length; j++) { + combination.push(ops[(i / Math.pow(3, j)) % 3 | 0]); + } + combinations.push(combination); + } - // Find the last file block index - let lastFileIndex = disk.length - 1; - while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) { - lastFileIndex--; - } + return combinations; +}; - if (lastFileIndex <= leftmostFreeIndex) { - // No file blocks to move - break; - } +// Concatenate two numbers if the operator is '||' +const concatenate = (num1, num2) => { + return parseInt(num1.toString() + num2.toString()); +}; - // Move the last file block to the leftmost free space - disk[leftmostFreeIndex] = disk[lastFileIndex]; - disk[lastFileIndex] = -1; - - // Set moved flag to true to keep going - moved = true; - } +// Modify the evaluate function to handle '||' operator (concatenation) +const evaluateExpressionWithConcatenation = (numbers, operators) => { + return numbers.reduce((result, num, index) => { + if (index === 0) return num; + const operator = operators[index - 1]; + if (operator === '+') return result + num; + if (operator === '*') return result * num; + if (operator === '||') return concatenate(result, num); + return result; + }, 0); +}; - return disk; +// Check if an equation can be solved with the given numbers and test value +const isValidEquation = (testValue, numbers) => { + const operatorCombinations = generateOperatorCombinations(numbers.length - 1); + return operatorCombinations.some(operators => { + const result = evaluateExpressionWithConcatenation(numbers, operators); + return result === testValue; + }); }; -// Helper function to calculate the checksum of the compacted disk -const calculateChecksum = (disk) => { - return disk.reduce((checksum, block, index) => { - if (block !== -1) { - checksum += index * block; // Sum the product of position and file ID - } - return checksum; - }, 0); +// Calculate the total calibration result for valid equations +const calculateTotalCalibration = (filePath) => { + const equations = readInput(filePath); + return equations.reduce((sum, { testValue, numbers }) => { + if (isValidEquation(testValue, numbers)) { + return sum + testValue; + } + return sum; + }, 0); }; -// Main function to orchestrate the solution -const calculateDiskChecksum = (filePath) => { - const input = fs.readFileSync(filePath, 'utf-8').trim(); +// Execute the function and output the result +const result = calculateTotalCalibration('input.txt'); +console.log(result);",node:14 +2024,15,1,"--- Day 15: Warehouse Woes --- - // Step 1: Parse the disk map into the initial disk representation - let disk = parseDiskMap(input); +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? - // Step 2: Compact the disk by moving file blocks to the leftmost free space - disk = compactDisk(disk); +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. - // Step 3: Calculate and return the checksum - return calculateChecksum(disk); -}; +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! -// Output the resulting checksum -const checksum = calculateDiskChecksum('input.txt'); -console.log(checksum);",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. -He shows you the disk map (your puzzle input) he's already generated. For example: +For example: -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +Here is a smaller example to get started: -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"const fs = require('fs'); +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -// Read and parse the input from the file -const getInput = (filePath) => { - const input = fs.readFileSync(filePath, 'utf-8').trim(); - return input.split('').map(Number); // Convert the input to an array of numbers -}; +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -// Build the initial disk state (alternating files and free spaces) -const buildDiskState = (diskLengths) => { - let disk = []; - let fileId = 0; - let isFile = true; +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - for (let length of diskLengths) { - if (isFile) { - disk.push(...Array(length).fill(fileId)); // Add file blocks - fileId++; - } else { - disk.push(...Array(length).fill(-1)); // Add free space blocks - } - isFile = !isFile; // Toggle between file and free space - } +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - return disk; -}; +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -// Compact the disk by moving file blocks to the leftmost available free space -const compactDisk = (disk) => { - let moved = true; +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## - while (moved) { - moved = false; +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## - const leftmostFreeIndex = disk.indexOf(-1); - if (leftmostFreeIndex === -1) break; // No free space left to move files into +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## - // Find the last file block's index - let lastFileIndex = disk.length - 1; - while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) { - lastFileIndex--; - } +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## - // If no file blocks to move, stop the process - if (lastFileIndex <= leftmostFreeIndex) break; +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## - // Move the last file block to the leftmost free space - disk[leftmostFreeIndex] = disk[lastFileIndex]; - disk[lastFileIndex] = -1; // Mark the last file block position as free +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## - moved = true; // Continue compacting - } +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## - return disk; -}; +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: -// Calculate the checksum by summing the product of positions and file IDs -const calculateChecksum = (disk) => { - return disk.reduce((checksum, fileId, index) => { - if (fileId !== -1) { - checksum += index * fileId; // Multiply position by file ID and sum - } - return checksum; - }, 0); -}; +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) -// Main function to orchestrate the disk processing and checksum calculation -const processDisk = (filePath) => { - const diskLengths = getInput(filePath); // Step 1: Get and parse the disk map - let disk = buildDiskState(diskLengths); // Step 2: Build the initial disk state +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. - disk = compactDisk(disk); // Step 3: Compact the disk to remove free space +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. - const checksum = calculateChecksum(disk); // Step 4: Calculate the checksum +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"const fs = require('fs'); - return checksum; +const charMap = { + ""^"": [0, -1], + "">"": [1, 0], + ""<"": [-1, 0], + ""v"": [0, 1] }; -// Run the function and print the resulting checksum -const checksum = processDisk('input.txt'); -console.log(checksum);",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +let warehouse = []; +let warehouseDone = false; +let moves = []; +let robotX = 0; +let robotY = 0; +let y = 0; -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. +const input = fs.readFileSync('input.txt', 'utf-8').split('\n'); +input.forEach(line => { + line = line.trim(); + if (line !== """") { + if (line.includes(""@"")) { + robotX = line.indexOf(""@""); + robotY = y; + } + if (warehouseDone) { + moves.push(...line.split('').map(c => charMap[c])); + } else { + warehouse.push([...line]); + } + } else { + warehouseDone = true; + } + y++; +}); -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +const width = warehouse[0].length; +const height = warehouse.length; +warehouse[robotY][robotX] = "".""; -He shows you the disk map (your puzzle input) he's already generated. For example: +function canMove(x, y, direction) { + while (0 <= x && x < width && 0 <= y && y < height) { + x += direction[0]; + y += direction[1]; + if (warehouse[y][x] === ""#"") return false; + if (warehouse[y][x] === ""."") return true; + } + return false; +} -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. +function moveRobot(x, y) { + moves.forEach(move => { + if (canMove(x, y, move)) { + let yy = y + move[1]; + let xx = x + move[0]; + if (warehouse[yy][xx] !== ""."") { + while (warehouse[yy + move[1]][xx + move[0]] !== ""."") { + xx += move[0]; + yy += move[1]; + } -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + const temp = warehouse[yy + move[1]][xx + move[0]]; + warehouse[yy + move[1]][xx + move[0]] = warehouse[y + move[1]][x + move[0]]; + warehouse[y + move[1]][x + move[0]] = temp; + } -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: + x += move[0]; + y += move[1]; + } + }); +} -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +moveRobot(robotX, robotY); -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +let result = 0; +warehouse.forEach((line, y) => { + line.forEach((char, x) => { + if (char === ""O"") { + result += 100 * y + x; + } + }); +}); -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +console.log(`result=${result}`);",node:14 +2024,15,1,"--- Day 15: Warehouse Woes --- -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +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? -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"const fs = require('fs'); +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! -// Load the disk map from the input file -const loadInput = (filePath) => fs.readFileSync(filePath, 'utf8').trim(); +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. -// Parse the disk map into blocks -const parseBlocks = (diskMap) => { - const blocks = []; - let isFile = true; - let fileId = 0; +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. - for (const char of diskMap) { - const length = parseInt(char, 10); - if (isFile) { - for (let i = 0; i < length; i++) blocks.push(fileId); - fileId++; - } else { - for (let i = 0; i < length; i++) blocks.push(-1); - } - isFile = !isFile; - } +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. - return blocks; -}; +For example: -// Compact the disk by moving file blocks to the leftmost free space -const compactBlocks = (blocks) => { - while (true) { - const freeIndex = blocks.indexOf(-1); - if (freeIndex === -1) break; +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## - let lastFileIndex = blocks.length - 1; - while (lastFileIndex > freeIndex && blocks[lastFileIndex] === -1) lastFileIndex--; +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. - if (lastFileIndex <= freeIndex) break; +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) - blocks[freeIndex] = blocks[lastFileIndex]; - blocks[lastFileIndex] = -1; - } +Here is a smaller example to get started: - return blocks; -}; +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -// Calculate the checksum of the compacted disk -const computeChecksum = (blocks) => { - return blocks.reduce((sum, block, index) => (block !== -1 ? sum + index * block : sum), 0); -}; +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: -// Main function to execute the solution -const main = () => { - const diskMap = loadInput('input.txt'); - const blocks = parseBlocks(diskMap); - const compactedBlocks = compactBlocks(blocks); - const checksum = computeChecksum(compactedBlocks); - console.log(checksum); -}; +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -// Run the program -main();",node:14 -2024,9,1,"--- Day 9: Disk Fragmenter --- +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -He shows you the disk map (your puzzle input) he's already generated. For example: +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.)",6421128769094,"// Read the input disk map as a string -const fs = require('fs'); -const input = fs.readFileSync('input.txt', 'utf-8').trim(); +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## -// Parse the disk map into file lengths and free space lengths -const diskLengths = input.split('').map(Number); -let disk = []; -let fileId = 0; -let isFile = true; +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## -// Build the initial disk representation -for (let i = 0; i < diskLengths.length; i++) { - const length = diskLengths[i]; - if (isFile) { - // Add blocks for the current file with the file ID - for (let j = 0; j < length; j++) { - disk.push(fileId); - } - fileId++; - } else { - // Add free space blocks represented by -1 - for (let j = 0; j < length; j++) { - disk.push(-1); - } - } - // Alternate between file and free space - isFile = !isFile; -} +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: -// Simulate moving file blocks one at a time from the end to the leftmost free space -while (true) { - // Find the leftmost free space index - let leftmostFreeIndex = disk.indexOf(-1); - if (leftmostFreeIndex === -1) { - // No free space left, disk is compacted - break; - } +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) - // Find the last file block index - let lastFileIndex = disk.length - 1; - while (lastFileIndex > leftmostFreeIndex && disk[lastFileIndex] === -1) { - lastFileIndex--; - } +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. - if (lastFileIndex <= leftmostFreeIndex) { - // No file blocks to move - break; - } +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. - // Move the last file block to the leftmost free space - disk[leftmostFreeIndex] = disk[lastFileIndex]; - disk[lastFileIndex] = -1; -} +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"const fs = require('fs'); -// Calculate the filesystem checksum -let checksum = 0; -for (let i = 0; i < disk.length; i++) { - if (disk[i] !== -1) { - // Sum the product of position and file ID - checksum += i * disk[i]; +const movementDict = { + v: [1, 0], + '^': [-1, 0], + '>': [0, 1], + '<': [0, -1] +}; + +function readInputFile() { + const data = fs.readFileSync('/Users/WW/Supahands/aoc-datasets/input.txt', 'utf8'); + const lines = data.split('\n'); + const warehouseMap = []; + let movements = ''; + let curPos = [0, 0]; + + let i = 0; + while (lines[i] !== '') { + if (lines[i].includes('@')) { + curPos = [i, lines[i].indexOf('@')]; } + warehouseMap.push(lines[i].split('')); + i++; + } + + i++; + while (i < lines.length) { + movements += lines[i]; + i++; + } + + return { warehouseMap, movements, curPos }; } -// Output the resulting checksum -console.log(checksum);",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- - -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. - -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +function findOpenSpot(pos, move, warehouseMap) { + while (true) { + pos = [pos[0] + move[0], pos[1] + move[1]]; + const posValue = warehouseMap[pos[0]]?.[pos[1]]; + if (posValue === '#') return false; + if (posValue === '.') return pos; + } +} -He shows you the disk map (your puzzle input) he's already generated. For example: +function main() { + const { warehouseMap, movements, curPos } = readInputFile(); + let total = 0; + let curPosLoc = curPos; + + for (const move of movements) { + const destination = [ + curPosLoc[0] + movementDict[move][0], + curPosLoc[1] + movementDict[move][1] + ]; + const destinationValue = warehouseMap[destination[0]]?.[destination[1]]; + + if (destinationValue === 'O') { + const openSpot = findOpenSpot(destination, movementDict[move], warehouseMap); + if (openSpot) { + warehouseMap[openSpot[0]][openSpot[1]] = 'O'; + warehouseMap[destination[0]][destination[1]] = '@'; + warehouseMap[curPosLoc[0]][curPosLoc[1]] = '.'; + curPosLoc = destination; + } + } else if (destinationValue === '.') { + warehouseMap[destination[0]][destination[1]] = '@'; + warehouseMap[curPosLoc[0]][curPosLoc[1]] = '.'; + curPosLoc = destination; + } + } -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. + for (let i = 0; i < warehouseMap.length; i++) { + for (let j = 0; j < warehouseMap[i].length; j++) { + if (warehouseMap[i][j] === 'O') { + total += 100 * i + j; + } + } + } -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). + console.log(`The sum of all boxes' GPS coordinates is ${total}`); +} -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: +main();",node:14 +2024,15,1,"--- Day 15: Warehouse Woes --- -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +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? -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. -Your puzzle answer was 6421128769094. +For example: ---- Part Two --- +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## -Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. -The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) -This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. +Here is a smaller example to get started: -The first example from above now proceeds differently: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -00...111...2...333.44.5555.6666.777.888899 -0099.111...2...333.44.5555.6666.777.8888.. -0099.1117772...333.44.5555.6666.....8888.. -0099.111777244.333....5555.6666.....8888.. -00992111777.44.333....5555.6666.....8888.. -The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: -Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require('fs'); -const path = require('path'); +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -// Parse the disk map into a memory map array, alternating between files and free space -function parseDiskMap(input) { - if (!input) return []; - - let memoryMap = []; - let isFile = true; - let fileID = 0; - - for (const char of input) { - const length = Number(char); - - if (isNaN(length)) { - console.error(`Invalid character in disk map: ${char}`); - process.exit(1); - } - - if (isFile) { - memoryMap.push(...Array(length).fill(fileID)); - fileID++; - } else { - memoryMap.push(...Array(length).fill(-1)); // Free space - } - - isFile = !isFile; // Alternate between file and free space - } - - return memoryMap; -} +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -// Part 2: Compact the disk by moving entire files to the leftmost free space -function compactify2(memoryMap) { - let files = []; - let currentFileID = null; - let currentSize = 0; +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - // Extract files from the memory map - for (let i = 0; i <= memoryMap.length; i++) { - const block = memoryMap[i]; - - if (block !== currentFileID && currentFileID !== null) { - files.push({ id: currentFileID, size: currentSize }); - currentFileID = null; - currentSize = 0; - } - - if (block !== -1 && currentFileID === null) { - currentFileID = block; - currentSize = 1; - } else if (block === currentFileID) { - currentSize++; - } - } - - // Sort files by descending ID - files.sort((a, b) => b.id - a.id); +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - // Move files to the leftmost available free space - files.forEach(file => { - const { id, size } = file; - let targetStart = -1; - let gapLength = 0; - - // Find the leftmost space for the file - for (let i = 0; i < memoryMap.length; i++) { - if (memoryMap[i] === -1) { - gapLength++; - if (gapLength === size) { - targetStart = i - size + 1; - break; - } - } else { - gapLength = 0; - } - } - - if (targetStart === -1) return; // No space found - - // Move the file blocks to the found space - const filePositions = []; - for (let i = 0; i < memoryMap.length; i++) { - if (memoryMap[i] === id) filePositions.push(i); - } +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - if (filePositions.length !== size) { - console.error(`Mismatch in file size for file ID ${id}`); - process.exit(1); - } +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - const firstFileBlock = filePositions[0]; - if (firstFileBlock < targetStart) return; // No need to move - - for (let j = 0; j < size; j++) { - memoryMap[targetStart + j] = id; - memoryMap[filePositions[j]] = -1; - } - }); +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - return memoryMap; -} +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -// Calculate the checksum of the memory map -function calculateChecksum(memoryMap, skipFree = false) { - return memoryMap.reduce((checksum, value, index) => { - if (skipFree && value === -1) return checksum; - if (!skipFree || value !== -1) { - checksum += index * value; - } - return checksum; - }, 0); -} +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -// Main function -function main() { - const filePath = path.join(__dirname, 'input.txt'); - - // Read input file - let content; - try { - content = fs.readFileSync(filePath, 'utf-8').trim(); - } catch (err) { - console.error(`Error reading input file: ${err.message}`); - process.exit(1); - } +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## - // Parse the disk map - const memoryMap = parseDiskMap(content); - - // Prepare separate copies for part 1 and part 2 - const memoryMapPart1 = [...memoryMap]; - const memoryMapPart2 = [...memoryMap]; +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## - // Part 2: Compact by moving entire files - compactify2(memoryMapPart2); +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## - // Part 2 Checksum Calculation - const part2Checksum = calculateChecksum(memoryMapPart2, true); - console.log(`Part 2 Checksum: ${part2Checksum}`); -} +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## -// Execute the program -main();",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: -He shows you the disk map (your puzzle input) he's already generated. For example: +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"const fs = require('fs'); -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +const input = fs.readFileSync('input.txt', 'utf-8').split('\n'); -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +let warehouseMap = []; +let movements = """"; +let curPos = [0, 0]; +let total = 0; -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +const movementDict = { + ""v"": [1, 0], + ""^"": [-1, 0], + "">"": [0, 1], + ""<"": [0, -1] +}; -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +function findOpenSpot(pos, move) { + while (true) { + pos = [pos[0] + move[0], pos[1] + move[1]]; + const posValue = warehouseMap[pos[0]][pos[1]]; + if (posValue === ""#"") return false; + else if (posValue === ""."") return pos; + } +} -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +let i = 0; +while (input[i] !== """") { + if (input[i].includes(""@"")) { + curPos = [i, input[i].indexOf(""@"")]; + } + warehouseMap.push(input[i].split('')); + i++; +} -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) +i++; +while (i < input.length) { + movements += input[i]; + i++; +} -Your puzzle answer was 6421128769094. +for (const move of movements) { + const destination = [curPos[0] + movementDict[move][0], curPos[1] + movementDict[move][1]]; + const destinationValue = warehouseMap[destination[0]][destination[1]]; + + if (destinationValue === ""O"") { + const openSpot = findOpenSpot(destination, movementDict[move]); + if (openSpot) { + warehouseMap[openSpot[0]][openSpot[1]] = ""O""; + warehouseMap[destination[0]][destination[1]] = ""@""; + warehouseMap[curPos[0]][curPos[1]] = "".""; + curPos = destination; + } + } else if (destinationValue === ""."") { + warehouseMap[destination[0]][destination[1]] = ""@""; + warehouseMap[curPos[0]][curPos[1]] = "".""; + curPos = destination; + } +} ---- Part Two --- +for (let i = 0; i < warehouseMap.length; i++) { + for (let j = 0; j < warehouseMap[i].length; j++) { + if (warehouseMap[i][j] === ""O"") { + total += 100 * i + j; + } + } +} -Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? +console.log(`The sum of all boxes' GPS coordinates is ${total}`);",node:14 +2024,15,1,"--- Day 15: Warehouse Woes --- -The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. +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? -This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. -The first example from above now proceeds differently: +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! -00...111...2...333.44.5555.6666.777.888899 -0099.111...2...333.44.5555.6666.777.8888.. -0099.1117772...333.44.5555.6666.....8888.. -0099.111777244.333....5555.6666.....8888.. -00992111777.44.333....5555.6666.....8888.. -The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. -Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require(""fs""); -const inputText = ""./input.txt""; +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. -fs.readFile(inputText, ""utf8"", (err, data) => { - if (err) { - console.error('Error reading file:', err); - return; - } - - data = data.split("""").map(Number); +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. - console.log(part1(data)); - console.log(part2(data)); -}); +For example: -const checkSum = data => { - let checkSum = 0; - for (let i = 0; i < data.length; i++) { - if (!isNaN(data[i])) { - checkSum += Number(data[i]) * i; - } - } - return checkSum; -} +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## -const part1 = (data) => { - let rawData = []; - for (let i = 0; i < data.length; i++) { - const char = i % 2 === 0 - ? (i/2).toString() - : ""."" - rawData.push(...Array(data[i]).fill(char)); - } +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. - for (let i = 0; i < rawData.length; i++) { - if (rawData[i] === ""."" && rawData[i + 1]) { - if (rawData[rawData.length -1] === ""."") { - while (rawData[rawData.length - 1] === ""."") { - rawData.pop(); - } - } - rawData[i] = rawData.pop(); - } - } - return checkSum(rawData.filter(num => !isNaN(Number(num)))); -} +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) -const part2 = (data) => { - let rawData = []; - for (let i = 0; i < data.length; i++) { - const char = i % 2 === 0 - ? (i/2).toString() - : ""."" - rawData.push(new Array(data[i]).fill(char)) - } +Here is a smaller example to get started: - if (rawData[rawData.length - 1].includes(""."")) rawData.pop(); +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - for (let i = rawData.length - 1; i >= 0; i--) { - if (!rawData[i].length || rawData[i][0] === ""."") continue; - - let firstMatchingIndex = rawData.findIndex((item, index) => item.length >= rawData[i].length && item[0] === ""."" && index < i); - if (firstMatchingIndex === -1) { - continue; - } else { - // if it can be swapped directly, swap it - if (rawData[i].length === rawData[firstMatchingIndex].length) { - [rawData[firstMatchingIndex], rawData[i]] = [rawData[i], rawData[firstMatchingIndex]]; - } else { - const dotsToAdd = new Array(rawData[firstMatchingIndex].length - rawData[i].length).fill("".""); - // i is the numbers, firstMatchingINdex is the dots - let numsToMove = rawData[i]; - rawData[i] = rawData[firstMatchingIndex].slice(0, rawData[i].length); - rawData[firstMatchingIndex] = numsToMove; - rawData.splice(firstMatchingIndex + 1, 0, dotsToAdd); - } - } - } - return checkSum(rawData.flat()); -}",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -He shows you the disk map (your puzzle input) he's already generated. For example: +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## -Your puzzle answer was 6421128769094. +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## ---- Part Two --- +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## -Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: -The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) -This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. -The first example from above now proceeds differently: +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. -00...111...2...333.44.5555.6666.777.888899 -0099.111...2...333.44.5555.6666.777.8888.. -0099.1117772...333.44.5555.6666.....8888.. -0099.111777244.333....5555.6666.....8888.. -00992111777.44.333....5555.6666.....8888.. -The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"const fs = require('fs'); -Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require('fs'); -const path = require('path'); +// Read and parse the input +const adv_input = fs.readFileSync('input.txt', 'utf-8'); +let [gridPart, steps_list] = adv_input.split(""\n\n""); +const step_lines = steps_list.split(/\r?\n/).filter(line => line.trim().length > 0); +let steps = step_lines.map(line => line.trim()).join(""""); -/** - * Parses the disk map string into an array of blocks. - * Files are represented by their unique ID, and free spaces by -1. - * @param {string} input - The disk map string. - * @returns {number[]} - The memory map array. - */ -function parseDiskMap(input) { - if (input === '') { - return []; - } - const memoryMap = []; - let isFile = true; // Flag to alternate between file and free space - let fileID = 0; +let grid = gridPart.split(/\r?\n/).map(line => line.trim().split('')); +let grid2 = grid.map(row => row.slice()); - for (const char of input) { - const length = parseInt(char, 10); - if (isNaN(length)) { - console.error(`Invalid character in disk map: ${char}`); - process.exit(1); - } +const shape = grid.length; +const directions = { ""^"": [-1, 0], ""v"": [1, 0], "">"": [0, 1], ""<"": [0, -1] }; - if (isFile) { - // Assign fileID to the next 'length' blocks - for (let i = 0; i < length; i++) { - memoryMap.push(fileID); - } - fileID++; +function next_step(grid, current_pos, step) { + const [x, y] = current_pos; + const [dx, dy] = directions[step]; + const nx = x + dx; + const ny = y + dy; + if (grid[nx][ny] === ""#"") { + return [x, y]; + } else if (grid[nx][ny] === ""O"") { + const next_block_pos = next_step(grid, [nx, ny], step); + if (next_block_pos[0] !== nx || next_block_pos[1] !== ny) { + grid[nx][ny] = grid[x][y]; + grid[x][y] = "".""; + return [nx, ny]; } else { - // Assign -1 (free space) to the next 'length' blocks - for (let i = 0; i < length; i++) { - memoryMap.push(-1); - } + return [x, y]; } - - // Toggle between file and free space - isFile = !isFile; + } else if (grid[nx][ny] === ""."") { + grid[nx][ny] = grid[x][y]; + grid[x][y] = "".""; + return [nx, ny]; } - - return memoryMap; } -/** - * Part 2: Move entire files to the leftmost possible free space that can fit them. - * Files are processed in order of decreasing file ID. - * @param {number[]} memoryMap - The memory map array. - * @returns {number[]} - The updated memory map after compaction. - */ -function compactify2(memoryMap) { - // Identify all files with their IDs and sizes - const files = []; - let currentFileID = null; - let currentSize = 0; - - for (let i = 0; i <= memoryMap.length; i++) { - const block = memoryMap[i]; - if (block !== currentFileID && currentFileID !== null) { - // End of the current file - files.push({ id: currentFileID, size: currentSize }); - currentFileID = null; - currentSize = 0; - } - if (block !== -1 && currentFileID === null) { - // Start of a new file - currentFileID = block; - currentSize = 1; - } else if (block === currentFileID) { - // Continuation of the current file - currentSize++; +function main(grid, steps) { + let init_pos; + for (let i = 0; i < shape; i++) { + for (let j = 0; j < shape; j++) { + if (grid[i][j] === ""@"") { + init_pos = [i, j]; + } } } - // Sort files by decreasing file ID - files.sort((a, b) => b.id - a.id); - - for (const file of files) { - const { id, size } = file; - - // Find the leftmost span of free space that can fit the entire file - let targetStart = -1; - let gapLength = 0; + let current_pos = init_pos; + for (const step of steps) { + current_pos = next_step(grid, current_pos, step); + } - for (let i = 0; i < memoryMap.length; i++) { - if (memoryMap[i] === -1) { - gapLength++; - if (gapLength === size) { - targetStart = i - size + 1; - break; - } - } else { - gapLength = 0; + let result = 0; + for (let x = 0; x < shape; x++) { + for (let y = 0; y < shape; y++) { + if (grid[x][y] === ""O"") { + result += 100 * x + y; } } + } - if (targetStart === -1) { - // No suitable free space found - continue; - } - - // Find the current positions of the file blocks - const filePositions = []; - for (let i = 0; i < memoryMap.length; i++) { - if (memoryMap[i] === id) { - filePositions.push(i); - } - } + return result; +} - if (filePositions.length !== size) { - console.error(`Mismatch in file size for file ID ${id}`); - process.exit(1); - } +console.log(`Result: ${main(grid, steps)}`);",node:14 +2024,15,1,"--- Day 15: Warehouse Woes --- - const firstFileBlock = filePositions[0]; - if (firstFileBlock < targetStart) { - // The file is already to the left; no need to move - continue; - } +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? - // Move the file blocks to the targetStart - for (let j = 0; j < size; j++) { - memoryMap[targetStart + j] = id; - memoryMap[filePositions[j]] = -1; - } - } +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. - return memoryMap; -} +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! -/** - * Calculates the filesystem checksum. - * @param {number[]} memoryMap - The memory map array. - * @param {boolean} skipFree - Whether to skip free spaces (-1). - * @returns {number} - The calculated checksum. - */ -function calculateChecksum(memoryMap, skipFree = false) { - let checksum = 0; - for (let i = 0; i < memoryMap.length; i++) { - const value = memoryMap[i]; - if (skipFree && value === -1) { - continue; - } - if (!skipFree || value !== -1) { - checksum += i * value; - } - } - return checksum; -} +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. -/** - * Main function to execute the disk compaction and checksum calculation. - */ -function main() { - // Read the input disk map from 'input.txt' - const filePath = path.join(__dirname, 'input.txt'); - let content; - try { - content = fs.readFileSync(filePath, 'utf-8').trim(); - } catch (err) { - console.error(`Error reading input file: ${err.message}`); - process.exit(1); - } +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. - // Parse the disk map - const memoryMap = parseDiskMap(content); +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. - // Clone the memory map for Part 1 and Part 2 - const oneMemoryMap = [...memoryMap]; - const twoMemoryMap = [...memoryMap]; +For example: - console.log(`\nInitial Memory Map:`); - console.log(oneMemoryMap.map(block => (block === -1 ? '.' : block)).join('')); +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## - // Part 2: Compact by moving entire files - console.log(`\n--- Part 2: Moving Entire Files ---`); - console.log(`Started Memory Map Length: ${twoMemoryMap.length}`); - compactify2(twoMemoryMap); - console.log(`Ended Memory Map Length: ${twoMemoryMap.length}`); - console.log(`Final Memory Map after Part 2:`); - console.log(twoMemoryMap.map(block => (block === -1 ? '.' : block)).join('')); +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. - // Calculate Part 2 Checksum - let sumPart2 = 0; - for (let pos = 0; pos < twoMemoryMap.length; pos++) { - const value = twoMemoryMap[pos]; - if (value === -1) { - continue; // Skip free spaces - } - sumPart2 += pos * value; - } - console.log(`Part 2 Checksum: ${sumPart2}`); -} +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) -// Execute the main function -main();",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- +Here is a smaller example to get started: -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: -He shows you the disk map (your puzzle input) he's already generated. For example: +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -Your puzzle answer was 6421128769094. +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## ---- Part Two --- +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## -Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## -The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## -This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## -The first example from above now proceeds differently: +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: -00...111...2...333.44.5555.6666.777.888899 -0099.111...2...333.44.5555.6666.777.8888.. -0099.1117772...333.44.5555.6666.....8888.. -0099.111777244.333....5555.6666.....8888.. -00992111777.44.333....5555.6666.....8888.. -The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) -Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require(""fs""); -const inputText = ""./input.txt""; +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. -// Asynchronous file reading and processing -const processFile = (filePath) => { - fs.readFile(filePath, ""utf8"", (err, data) => { - if (err) { - console.error(""Error reading file:"", err); - return; - } +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. - const parsedData = parseInputData(data); - console.log(computePart1(parsedData)); - console.log(computePart2(parsedData)); - }); -}; +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?",1499739,"const fs = require('fs'); -// Parse the input data into an array of numbers -const parseInputData = (data) => { - return data.split("""").map(Number); +const charMap = { + '^': [0, -1], + '>': [1, 0], + '<': [-1, 0], + 'v': [0, 1] }; -// Helper function to compute checksum -const calculateChecksum = (data) => { - return data.reduce((sum, value, index) => { - if (!isNaN(value)) { - return sum + value * index; +function canMove(x, y, direction, width, height, warehouse) { + while (x >= 0 && x < width && y >= 0 && y < height) { + x += direction[0]; + y += direction[1]; + if (warehouse[y][x] === '#') { + return false; + } + if (warehouse[y][x] === '.') { + return true; } - return sum; - }, 0); -}; - -// Part 1 computation logic -const computePart1 = (data) => { - let rawData = createInitialRawData(data); - - // Perform the file-block shifting logic - rawData = moveFileBlocks(rawData); - - // Filter out non-numeric values and calculate checksum - const numericData = rawData.filter(value => !isNaN(Number(value))); - return calculateChecksum(numericData); -}; - -// Helper function to create the initial raw data -const createInitialRawData = (data) => { - let rawData = []; - for (let i = 0; i < data.length; i++) { - const char = i % 2 === 0 ? (i / 2).toString() : "".""; - rawData.push(...Array(data[i]).fill(char)); } - return rawData; -}; + return false; +} -// Helper function to shift file blocks -const moveFileBlocks = (rawData) => { - for (let i = 0; i < rawData.length; i++) { - if (rawData[i] === ""."" && rawData[i + 1]) { - if (rawData[rawData.length - 1] === ""."") { - while (rawData[rawData.length - 1] === ""."") { - rawData.pop(); +function moveRobot(x, y, moves, warehouse, width, height) { + for (const move of moves) { + if (canMove(x, y, move, width, height, warehouse)) { + let yy = y + move[1]; + let xx = x + move[0]; + if (warehouse[yy][xx] !== '.') { + while (warehouse[yy + move[1]]?.[xx + move[0]] !== '.') { + xx += move[0]; + yy += move[1]; } + [warehouse[yy + move[1]][xx + move[0]], warehouse[y + move[1]][x + move[0]]] = [warehouse[y + move[1]][x + move[0]], warehouse[yy + move[1]][xx + move[0]]]; } - rawData[i] = rawData.pop(); + x += move[0]; + y += move[1]; } } - return rawData; -}; +} -// Part 2 computation logic -const computePart2 = (data) => { - let rawData = create2DInitialRawData(data); - - // Remove unnecessary trailing empty slots - if (rawData[rawData.length - 1].includes(""."")) rawData.pop(); +function main() { + const data = fs.readFileSync('input.txt', 'utf8').split('\n'); + let warehouse = []; + let moves = []; + let robotX = 0, robotY = 0; + let warehouseDone = false; + + for (let y = 0; y < data.length; y++) { + const line = data[y].trim(); + if (line !== '') { + if (line.includes('@')) { + robotX = line.indexOf('@'); + robotY = y; + } + if (warehouseDone) { + moves.push(...line.split('').map(c => charMap[c])); + } else { + warehouse.push(line.split('')); + } + } else { + warehouseDone = true; + } + } - // Perform file swapping and shifting - rawData = swapAndShiftFiles(rawData); + const width = warehouse[0].length; + const height = warehouse.length; + warehouse[robotY][robotX] = '.'; - // Flatten the 2D array and calculate checksum - return calculateChecksum(rawData.flat()); -}; + moveRobot(robotX, robotY, moves, warehouse, width, height); -// Helper function to create the initial 2D raw data for part 2 -const create2DInitialRawData = (data) => { - let rawData = []; - for (let i = 0; i < data.length; i++) { - const char = i % 2 === 0 ? (i / 2).toString() : "".""; - rawData.push(new Array(data[i]).fill(char)); + let result = 0; + for (let y = 0; y < warehouse.length; y++) { + for (let x = 0; x < warehouse[y].length; x++) { + if (warehouse[y][x] === 'O') { + result += 100 * y + x; + } + } } - return rawData; -}; -// Helper function to swap and shift file blocks -const swapAndShiftFiles = (rawData) => { - for (let i = rawData.length - 1; i >= 0; i--) { - if (!rawData[i].length || rawData[i][0] === ""."") continue; + console.log(`result=${result}`); +} - const firstMatchingIndex = findMatchingFreeSpace(rawData, i); - if (firstMatchingIndex === -1) continue; +main();",node:14 +2024,15,2,"--- Day 15: Warehouse Woes --- - if (rawData[i].length === rawData[firstMatchingIndex].length) { - [rawData[firstMatchingIndex], rawData[i]] = [rawData[i], rawData[firstMatchingIndex]]; - } else { - const dotsToAdd = new Array(rawData[firstMatchingIndex].length - rawData[i].length).fill("".""); - let numsToMove = rawData[i]; - rawData[i] = rawData[firstMatchingIndex].slice(0, rawData[i].length); - rawData[firstMatchingIndex] = numsToMove; - rawData.splice(firstMatchingIndex + 1, 0, dotsToAdd); - } - } - return rawData; -}; +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? -// Helper function to find the first matching free space large enough to fit a file -const findMatchingFreeSpace = (rawData, currentIndex) => { - return rawData.findIndex((item, index) => item.length >= rawData[currentIndex].length && item[0] === ""."" && index < currentIndex); -}; +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. -// Execute the program -processFile(inputText);",node:14 -2024,9,2,"--- Day 9: Disk Fragmenter --- +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! -Another push of the button leaves you in the familiar hallways of some friendly amphipods! Good thing you each somehow got your own personal mini submarine. The Historians jet away in search of the Chief, mostly by driving directly into walls. +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. -While The Historians quickly figure out how to pilot these things, you notice an amphipod in the corner struggling with his computer. He's trying to make more contiguous free space by compacting all of the files, but his program isn't working; you offer to help. +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. -He shows you the disk map (your puzzle input) he's already generated. For example: +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. -2333133121414131402 -The disk map uses a dense format to represent the layout of files and free space on the disk. The digits alternate between indicating the length of a file and the length of free space. +For example: -So, a disk map like 12345 would represent a one-block file, two blocks of free space, a three-block file, four blocks of free space, and then a five-block file. A disk map like 90909 would represent three nine-block files in a row (with no free space between them). +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## -Each file on disk also has an ID number based on the order of the files as they appear before they are rearranged, starting with ID 0. So, the disk map 12345 has three files: a one-block file with ID 0, a three-block file with ID 1, and a five-block file with ID 2. Using one character for each block where digits are the file ID and . is free space, the disk map 12345 represents these individual blocks: +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. -0..111....22222 -The first example above, 2333133121414131402, represents these individual blocks: +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## -00...111...2...333.44.5555.6666.777.888899 -The amphipod would like to move file blocks one at a time from the end of the disk to the leftmost free space block (until there are no gaps remaining between file blocks). For the disk map 12345, the process looks like this: +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: -0..111....22222 -02.111....2222. -022111....222.. -0221112...22... -02211122..2.... -022111222...... -The first example requires a few more steps: +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) -00...111...2...333.44.5555.6666.777.888899 -009..111...2...333.44.5555.6666.777.88889. -0099.111...2...333.44.5555.6666.777.8888.. -00998111...2...333.44.5555.6666.777.888... -009981118..2...333.44.5555.6666.777.88.... -0099811188.2...333.44.5555.6666.777.8..... -009981118882...333.44.5555.6666.777....... -0099811188827..333.44.5555.6666.77........ -00998111888277.333.44.5555.6666.7......... -009981118882777333.44.5555.6666........... -009981118882777333644.5555.666............ -00998111888277733364465555.66............. -0099811188827773336446555566.............. -The final step of this file-compacting process is to update the filesystem checksum. To calculate the checksum, add up the result of multiplying each of these blocks' position with the file ID number it contains. The leftmost block is in position 0. If a block contains free space, skip it instead. +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. -Continuing the first example, the first few blocks' position multiplied by its file ID number are 0 * 0 = 0, 1 * 0 = 0, 2 * 9 = 18, 3 * 9 = 27, 4 * 8 = 32, and so on. In this example, the checksum is the sum of these, 1928. +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. -Compact the amphipod's hard drive using the process he requested. What is the resulting filesystem checksum? (Be careful copy/pasting the input for this puzzle; it is a single, very long line.) +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? -Your puzzle answer was 6421128769094. +Your puzzle answer was 1499739. --- Part Two --- -Upon completion, two things immediately become clear. First, the disk definitely has a lot more contiguous free space, just like the amphipod hoped. Second, the computer is running much more slowly! Maybe introducing all of that file system fragmentation was a bad idea? - -The eager amphipod already has a new plan: rather than move individual blocks, he'd like to try compacting the files on his disk by moving whole files instead. +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. -This time, attempt to move whole files to the leftmost span of free space blocks that could fit the file. Attempt to move each file exactly once in order of decreasing file ID number starting with the file with the highest file ID number. If there is no span of free space to the left of a file that is large enough to fit the file, the file does not move. +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. -The first example from above now proceeds differently: +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: -00...111...2...333.44.5555.6666.777.888899 -0099.111...2...333.44.5555.6666.777.8888.. -0099.1117772...333.44.5555.6666.....8888.. -0099.111777244.333....5555.6666.....8888.. -00992111777.44.333....5555.6666.....8888.. -The process of updating the filesystem checksum is the same; now, this example's checksum would be 2858. +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) -Start over, now compacting the amphipod's hard drive using this new method instead. What is the resulting filesystem checksum?",6448168620520,"const fs = require(""fs""); -const inputText = ""./input.txt""; +The larger example from before would now look like this: -// Read the input file and handle errors -function readInputFile(filePath) { - return new Promise((resolve, reject) => { - fs.readFile(filePath, ""utf8"", (err, data) => { - if (err) { - reject(`Error reading file: ${err}`); - } else { - resolve(data); - } - }); - }); -} +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: -// Helper function to calculate the checksum -function calculateChecksum(data) { - return data.reduce((checksum, value, index) => { - if (!isNaN(value)) { - checksum += Number(value) * index; - } - return checksum; - }, 0); -} +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### -// Part 1 logic: Process data into a new array, then calculate checksum -function processPart1(data) { - const rawData = []; - - data.forEach((value, index) => { - const char = index % 2 === 0 ? (index / 2).toString() : "".""; - rawData.push(...Array(value).fill(char)); - }); + !isNaN(Number(num)))); -} +Move <: +############## +##......##..## +##..........## +##...[][]@..## +##....[]....## +##..........## +############## -// Part 2 logic: Compact the array by moving file blocks to free space -function processPart2(data) { - const rawData = []; +Move v: +############## +##......##..## +##..........## +##...[][]...## +##....[].@..## +##..........## +############## - data.forEach((value, index) => { - const char = index % 2 === 0 ? (index / 2).toString() : "".""; - rawData.push(new Array(value).fill(char)); - }); +Move v: +############## +##......##..## +##..........## +##...[][]...## +##....[]....## +##.......@..## +############## - if (rawData[rawData.length - 1].includes(""."")) rawData.pop(); +Move <: +############## +##......##..## +##..........## +##...[][]...## +##....[]....## +##......@...## +############## - // Move files into the leftmost available spaces - for (let i = rawData.length - 1; i >= 0; i--) { - if (!rawData[i].length || rawData[i][0] === ""."") continue; +Move <: +############## +##......##..## +##..........## +##...[][]...## +##....[]....## +##.....@....## +############## - const firstMatchingIndex = rawData.findIndex((item, index) => { - return item.length >= rawData[i].length && item[0] === ""."" && index < i; - }); +Move ^: +############## +##......##..## +##...[][]...## +##....[]....## +##.....@....## +##..........## +############## - if (firstMatchingIndex !== -1) { - if (rawData[i].length === rawData[firstMatchingIndex].length) { - [rawData[firstMatchingIndex], rawData[i]] = [rawData[i], rawData[firstMatchingIndex]]; - } else { - const dotsToAdd = new Array(rawData[firstMatchingIndex].length - rawData[i].length).fill("".""); - const numsToMove = rawData[i]; - rawData[i] = rawData[firstMatchingIndex].slice(0, rawData[i].length); - rawData[firstMatchingIndex] = numsToMove; - rawData.splice(firstMatchingIndex + 1, 0, dotsToAdd); - } - } - } +Move ^: +############## +##......##..## +##...[][]...## +##....[]....## +##.....@....## +##..........## +############## - return calculateChecksum(rawData.flat()); -} +Move <: +############## +##......##..## +##...[][]...## +##....[]....## +##....@.....## +##..........## +############## -// Main function to execute the program -async function main() { - try { - const data = await readInputFile(inputText); - const parsedData = data.split("""").map(Number); +Move <: +############## +##......##..## +##...[][]...## +##....[]....## +##...@......## +##..........## +############## - console.log(""Part 1 Checksum:"", processPart1(parsedData)); - console.log(""Part 2 Checksum:"", processPart2(parsedData)); - } catch (error) { - console.error(error); - } -} +Move ^: +############## +##......##..## +##...[][]...## +##...@[]....## +##..........## +##..........## +############## -// Run the main function -main();",node:14 -2024,10,1,"--- Day 10: Hoof It --- +Move ^: +############## +##...[].##..## +##...@.[]...## +##....[]....## +##..........## +##..........## +############## +This warehouse also uses GPS to locate the boxes. For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question. So, the box shown below has a distance of 1 from the top edge of the map and 5 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 5 = 105. -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. +########## +##...[]... +##........ +In the scaled-up version of the larger example from above, after the robot has finished all of its moves, the warehouse would look like this: -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. +#################### +##[].......[].[][]## +##[]...........[].## +##[]........[][][]## +##[]......[]....[]## +##..##......[]....## +##..[]............## +##..@......[].[][]## +##......[][]..[]..## +#################### +The sum of these boxes' GPS coordinates is 9021. -Perhaps you can help fill in the missing hiking trails? +Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes' final GPS coordinates?",1522215,"const fs = require('fs'); +const {log} = require('console'); -The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: +const [rawmap, rawinstructions] = fs.readFileSync('input.txt', 'utf-8') + .split('\n\n') +const instructions = rawinstructions.split('\n').flat().join().split(''); -0123 -1234 -8765 -9876 -Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). +function part1(){ -You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. + const maplines = rawmap.split('\n'); + const rows = maplines.length + const cols = maplines[0].length; -A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + const isWall = (r, c) => maplines[r][c] === '#'; + const isRobot = (r, c) => maplines[r][c] === '@'; + const isBox = (r, c) => maplines[r][c] === 'O'; + const isOpen = (r, c) => maplines[r][c] === '.'; + const replaceAt = (r, c, x) => { + maplines[r] = maplines[r].substring(0, c) + x + maplines[r].substring(c + 1); + } -This trailhead has a score of 2: + let robot; + for (let r = 0; r < maplines.length; r++) { + for (let c = 0; c < maplines[r].length; c++) { + if (isRobot(r, c)) { + robot = [r, c]; + break; + } + } + } + console.log(maplines, robot); + + for (let instruction of instructions) { + let cr = robot[0]; + let cc = robot[1]; + let boxesToMove = 0; + if (instruction === '^') { + for (let r = robot[0] - 1; r >= 0; r--) { + if (isWall(r, cc)) { + break; + } else if (isBox(r, cc)) { + boxesToMove++; + } else if (isOpen(r, cc)) { + if (boxesToMove > 0) { + replaceAt(r, cc, 'O'); + } + replaceAt(cr, cc, '.'); + replaceAt(cr - 1, cc, '@'); + robot = [cr - 1, cc]; + break; + } + } + } else if (instruction === 'v') { + for (let r = robot[0] + 1; r <= rows; r++) { + if (isWall(r, cc)) { + break; + } else if (isBox(r, cc)) { + boxesToMove++; + } else if (isOpen(r, cc)) { + if (boxesToMove > 0) { + replaceAt(r, cc, 'O'); + } + replaceAt(cr, cc, '.'); + replaceAt(cr + 1, cc, '@'); + robot = [cr + 1, cc]; + break; + } + } + } else if (instruction === '<') { + for (let c = robot[1] - 1; c >= 0; c--) { + if (isWall(cr, c)) { + break; + } else if (isBox(cr, c)) { + boxesToMove++; + } else if (isOpen(cr, c)) { + if (boxesToMove > 0) { + replaceAt(cr, c, 'O'); + } + replaceAt(cr, cc, '.'); + replaceAt(cr, cc - 1, '@'); + robot = [cr, cc - 1]; + break; + } + } + } else if (instruction === '>') { + for (let c = robot[1] + 1; c <= cols; c++) { + if (isWall(cr, c)) { + break; + } else if (isBox(cr, c)) { + boxesToMove++; + } else if (isOpen(cr, c)) { + if (boxesToMove > 0) { + replaceAt(cr, c, 'O'); + } + replaceAt(cr, cc, '.'); + replaceAt(cr, cc + 1, '@'); + robot = [cr, cc + 1]; + break; + } + } + } + } -...0... -...1... -...2... -6543456 -7.....7 -8.....8 -9.....9 -(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + let sum = 0; + for (let r = 0; r < maplines.length; r++) { + for (let c = 0; c < maplines[r].length; c++) { + if (isBox(r, c)) { + sum+= 100 * r + c; + } + } + } + console.log(sum); +} -This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: +function part2() { + const maplines = rawmap.split('\n'); + let m = []; + + for (let r = 0; r < maplines.length; r++) { + let ml = ''; + for (let c = 0; c < maplines[r].length; c++) { + if (maplines[r][c] === 'O') { + ml += '[]' + } else if (maplines[r][c] === '.') { + ml += '..' + } else if (maplines[r][c] === '#') { + ml += '##' + } else if (maplines[r][c] === '@') { + ml += '@.' + } + } + m.push(ml); + } -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + const rows = m.length + const cols = m[0].length; + + const isWall = (r, c) => m[r][c] === '#'; + const isRobot = (r, c) => m[r][c] === '@'; + const isBox = (r, c) => isLBox(r, c) || isRBox(r, c); + const isLBox = (r, c) => m[r][c] === '['; + const isRBox = (r, c) => m[r][c] === ']'; + const isOpen = (r, c) => m[r][c] === '.'; + const replaceAt = (r, c, x) => { + m[r] = m[r].substring(0, c) + x + m[r].substring(c + 1); + } -10..9.. -2...8.. -3...7.. -4567654 -...8..3 -...9..2 -.....01 -Here's a larger example: + const canBoxMoveUp = (r, c) => { + if (m[r - 1][c] === '#' || m[r - 1][c + 1] === '#') { + return false; + } + if (m[r - 1][c] === '.' && m[r - 1][c + 1] === '.') { + return true; + } + if (m[r - 1][c] === '[') { + // box right above + return canBoxMoveUp(r - 1, c); + } + if (m[r - 1][c] === ']' && m[r - 1][c + 1] === '[') { + // 2 boxes + return canBoxMoveUp(r - 1, c - 1) && canBoxMoveUp(r - 1, c + 1); + } + if (m[r - 1][c] === ']') { + return canBoxMoveUp(r - 1, c - 1); + } -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + if (m[r - 1][c + 1] === '[') { + return canBoxMoveUp(r - 1, c + 1); + } + } -The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"const fs = require('fs'); + const moveBoxUp = (r, c) => { + function move() { + replaceAt(r - 1, c, '['); + replaceAt(r - 1, c + 1, ']'); + replaceAt(r, c, '.'); + replaceAt(r, c + 1, '.'); + } -class Position { - constructor(row, col, height) { - this.row = row; - this.col = col; - this.height = height; + if (!isBox(r - 1, c) && !isBox(r - 1, c + 1)) { + move(); + } else { + if (isLBox(r - 1, c)) { + moveBoxUp(r - 1, c); + move(); + } else if (isRBox(r - 1, c) && isLBox(r - 1, c + 1)) { + moveBoxUp(r - 1, c - 1); + moveBoxUp(r - 1, c + 1); + move(); + } else if (isRBox(r - 1, c)) { + moveBoxUp(r - 1, c - 1); + move(); + } else if (isLBox(r - 1, c + 1)) { + moveBoxUp(r - 1, c + 1); + move(); + } + } } - toString() { - return `${this.row},${this.col}`; - } -} + const moveBoxDown = (r, c) => { + function move() { + replaceAt(r + 1, c, '['); + replaceAt(r + 1, c + 1, ']'); + replaceAt(r, c, '.'); + replaceAt(r, c + 1, '.'); + } -class HikingMap { - constructor(grid) { - this.grid = grid; - this.rows = grid.length; - this.cols = grid[0].length; - this.directions = [ - { dx: 0, dy: 1 }, // right - { dx: 1, dy: 0 }, // down - { dx: 0, dy: -1 }, // left - { dx: -1, dy: 0 } // up - ]; + if (!isBox(r + 1, c) && !isBox(r + 1, c + 1)) { + move(); + } else { + if (isLBox(r + 1, c)) { + moveBoxDown(r + 1, c); + move(); + } else if (isRBox(r + 1, c) && isLBox(r + 1, c + 1)) { + moveBoxDown(r + 1, c - 1); + moveBoxDown(r + 1, c + 1); + move(); + } else if (isRBox(r + 1, c)) { + moveBoxDown(r + 1, c - 1); + move(); + } else if (isLBox(r + 1, c + 1)) { + moveBoxDown(r + 1, c + 1); + move(); + } + } } - getHeight(row, col) { - return this.grid[row][col]; + const canBoxMoveDown = (r, c) => { + if (m[r + 1][c] === '#' || m[r + 1][c + 1] === '#') { + return false; + } + if (m[r + 1][c] === '.' && m[r + 1][c + 1] === '.') { + return true; + } + if (m[r + 1][c] === '[') { + // box right above + return canBoxMoveDown(r + 1, c); + } + if (m[r + 1][c] === ']' && m[r + 1][c + 1] === '[') { + // 2 boxes + return canBoxMoveDown(r + 1, c - 1) && canBoxMoveDown(r + 1, c + 1); + } + if (m[r + 1][c] === ']') { + return canBoxMoveDown(r + 1, c - 1); + } + + if (m[r + 1][c + 1] === '[') { + return canBoxMoveDown(r + 1, c + 1); + } } - isValidPosition(row, col) { - return row >= 0 && row < this.rows && col >= 0 && col < this.cols; + let robot; + for (let r = 0; r < m.length; r++) { + for (let c = 0; c < m[r].length; c++) { + if (isRobot(r, c)) { + robot = [r, c]; + break; + } + } } - findTrailheads() { - const trailheads = []; - for (let row = 0; row < this.rows; row++) { - for (let col = 0; col < this.cols; col++) { - if (this.getHeight(row, col) === 0) { - trailheads.push(new Position(row, col, 0)); + let index = 0; + for (let instruction of instructions) { + // console.log(m); + // console.log('====', index, '====', instruction); + index++; + let cr = robot[0]; + let cc = robot[1]; + let boxesToMove = []; + if (instruction === '^') { + const nextR = cr - 1; + if (isWall(nextR, cc)) continue; + if (isBox(nextR, cc)) { + if (isLBox(nextR, cc)) { + if (canBoxMoveUp(nextR, cc)) { + moveBoxUp(nextR, cc); + } else { + continue; + } + } else { + if (canBoxMoveUp(nextR, cc - 1)) { + moveBoxUp(nextR, cc - 1); + } else { + continue; + } + } + } + if (isOpen(nextR, cc) || isBox(nextR, cc)) { + replaceAt(cr, cc, '.'); + replaceAt(nextR, cc, '@'); + robot = [nextR, cc]; + } + } else if (instruction === 'v') { + const nextR = cr + 1; + if (isWall(nextR, cc)) continue; + if (isBox(nextR, cc)) { + if (isLBox(nextR, cc)) { + if (canBoxMoveDown(nextR, cc)) { + moveBoxDown(nextR, cc); + } else { + continue; + } + } else { + if (canBoxMoveDown(nextR, cc - 1)) { + moveBoxDown(nextR, cc - 1); + } else { + continue; + } + } + } + if (isOpen(nextR, cc) || isBox(nextR, cc)) { + replaceAt(cr, cc, '.'); + replaceAt(nextR, cc, '@'); + robot = [nextR, cc]; + } + } else if (instruction === '<') { + for (let c = robot[1] - 1; c >= 0; c--) { + if (isWall(cr, c)) { + break; + } else if (isLBox(cr, c)) { + boxesToMove.push([cr, c]); + } else if (isOpen(cr, c)) { + for (let b of boxesToMove) { + replaceAt(b[0], b[1] - 1, '['); + replaceAt(b[0], b[1], ']'); + } + replaceAt(cr, cc, '.'); + replaceAt(cr, cc - 1, '@'); + robot = [cr, cc - 1]; + break; + } + } + } else if (instruction === '>') { + for (let c = robot[1] + 1; c <= cols; c++) { + if (isWall(cr, c)) { + break; + } else if (isLBox(cr, c)) { + boxesToMove.push([cr, c]); + } else if (isOpen(cr, c)) { + for (let b of boxesToMove) { + replaceAt(b[0], b[1] + 1, '['); + replaceAt(b[0], b[1] + 2, ']'); + } + replaceAt(cr, cc, '.'); + replaceAt(cr, cc + 1, '@'); + robot = [cr, cc + 1]; + break; } } } - return trailheads; } - getNeighbors(position) { - return this.directions - .map(({ dx, dy }) => ({ - row: position.row + dx, - col: position.col + dy - })) - .filter(({ row, col }) => this.isValidPosition(row, col)) - .map(({ row, col }) => new Position(row, col, this.getHeight(row, col))); + console.log(m); + + let sum = 0; + for (let r = 0; r < m.length; r++) { + for (let c = 0; c < m[r].length; c++) { + if (isLBox(r, c)) { + sum += 100 * r + c; + } + } } + console.log(sum); } -class TrailFinder { - constructor(hikingMap) { - this.map = hikingMap; - this.reachableNines = new Set(); - this.visited = new Set(); - } +part2();",node:14 +2024,15,2,"--- Day 15: Warehouse Woes --- + +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? + +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. + +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! + +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. + +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. + +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. + +For example: + +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## + +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) - findTrailsFromPosition(position) { - this.reachableNines.clear(); - this.visited.clear(); - this.visited.add(position.toString()); - this.explorePaths(position); - return this.reachableNines.size; - } +Here is a smaller example to get started: - explorePaths(currentPos) { - if (currentPos.height === 9) { - this.reachableNines.add(currentPos.toString()); - return; - } +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - const neighbors = this.map.getNeighbors(currentPos); - - for (const neighbor of neighbors) { - const key = neighbor.toString(); - - if (!this.visited.has(key) && neighbor.height === currentPos.height + 1) { - this.visited.add(key); - this.explorePaths(neighbor); - this.visited.delete(key); - } - } - } -} +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: -class HikingTrailSolver { - static solve(inputFile) { - try { - const grid = this.parseInput(inputFile); - const hikingMap = new HikingMap(grid); - const trailFinder = new TrailFinder(hikingMap); - - return hikingMap.findTrailheads() - .map(trailhead => trailFinder.findTrailsFromPosition(trailhead)) - .reduce((sum, score) => sum + score, 0); - } catch (error) { - console.error('Error solving hiking trails:', error); - throw error; - } - } +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## - static parseInput(filename) { - const content = fs.readFileSync(filename, 'utf8').trim(); - return content.split('\n').map(line => - line.split('').map(Number) - ); - } -} +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -// Execute solution -try { - const result = HikingTrailSolver.solve('input.txt'); - console.log(`Sum of trailhead scores: ${result}`); -} catch (error) { - console.error('Failed to solve puzzle:', error); - process.exit(1); -}",node:14 -2024,10,1,"--- Day 10: Hoof It --- +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -Perhaps you can help fill in the missing hiking trails? +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -0123 -1234 -8765 -9876 -Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -This trailhead has a score of 2: +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## -...0... -...1... -...2... -6543456 -7.....7 -8.....8 -9.....9 -(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## -This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## -10..9.. -2...8.. -3...7.. -4567654 -...8..3 -...9..2 -.....01 -Here's a larger example: +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: -The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"const fs = require('fs'); +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) -function findTrailheadScores(map) { - const rows = map.length; - const cols = map[0].length; - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up - let totalScore = 0; +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. - // Find all trailheads (positions with height 0) - for (let r = 0; r < rows; r++) { - for (let c = 0; c < cols; c++) { - if (map[r][c] === 0) { - const score = calculateTrailheadScore(r, c, map); - totalScore += score; - } - } - } +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. - return totalScore; -} +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? -function calculateTrailheadScore(startRow, startCol, map) { - const rows = map.length; - const cols = map[0].length; - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; - const reachableNines = new Set(); // Store unique positions of reachable 9s +Your puzzle answer was 1499739. - // Use DFS to find all possible paths - function dfs(row, col, currentHeight, visited) { - // If we reached height 9, add position to reachableNines - if (map[row][col] === 9) { - reachableNines.add(`${row},${col}`); - return; - } +--- Part Two --- - // Try all directions - for (const [dr, dc] of directions) { - const newRow = row + dr; - const newCol = col + dc; +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. - // Check if new position is valid - if (newRow >= 0 && newRow < rows && - newCol >= 0 && newCol < cols && - !visited.has(`${newRow},${newCol}`)) { - - // Check if height increases by exactly 1 - if (map[newRow][newCol] === currentHeight + 1) { - visited.add(`${newRow},${newCol}`); - dfs(newRow, newCol, currentHeight + 1, visited); - visited.delete(`${newRow},${newCol}`); - } - } - } - } +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. - // Start DFS from the trailhead - const visited = new Set([`${startRow},${startCol}`]); - dfs(startRow, startCol, 0, visited); +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: - return reachableNines.size; -} +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) -// Read and parse input -function parseInput(filename) { - const input = fs.readFileSync(filename, 'utf8').trim(); - return input.split('\n').map(line => - line.split('').map(Number) - ); -} +The larger example from before would now look like this: -// Main execution -try { - const map = parseInput('input.txt'); - const result = findTrailheadScores(map); - console.log(`Sum of trailhead scores: ${result}`); -} catch (error) { - console.error('Error:', error.message); -}",node:14 -2024,10,1,"--- Day 10: Hoof It --- +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + { - try { - const input = fs.readFileSync(filename, 'utf8').trim(); - return input.split('\n').map(line => line.split('').map(Number)); - } catch (error) { - console.error('Error parsing input:', error.message); - throw error; - } -}; +#################### +##[].......[].[][]## +##[]...........[].## +##[]........[][][]## +##[]......[]....[]## +##..##......[]....## +##..[]............## +##..@......[].[][]## +##......[][]..[]..## +#################### +The sum of these boxes' GPS coordinates is 9021. -// Helper function to check if a given position is within bounds and valid for hiking -const isValidMove = (row, col, currentHeight, rows, cols, visited, map) => { - return ( - row >= 0 && row < rows && - col >= 0 && col < cols && - !visited.has(`${row},${col}`) && - map[row][col] === currentHeight + 1 - ); -}; +Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes' final GPS coordinates?",1522215,"function getNext(pos, move) { + const moveDict = {'^': [-1, 0], '>': [0, 1], 'v': [1, 0], '<': [0, -1]}; + return [pos[0] + moveDict[move][0], pos[1] + moveDict[move][1]]; +} -// Depth First Search (DFS) to explore hiking trails from a given start position -const dfs = (row, col, currentHeight, visited, rows, cols, directions, map, reachableNines) => { - if (map[row][col] === 9) { - reachableNines.add(`${row},${col}`); - return; +function getChars(c) { + if (c === '@') { + return '@.'; + } else if (c === 'O') { + return '[]'; + } else { + return c + c; } +} - // Explore in all 4 directions (right, down, left, up) - for (const [dr, dc] of directions) { - const newRow = row + dr; - const newCol = col + dc; - - if (isValidMove(newRow, newCol, currentHeight, rows, cols, visited, map)) { - visited.add(`${newRow},${newCol}`); - dfs(newRow, newCol, currentHeight + 1, visited, rows, cols, directions, map, reachableNines); - visited.delete(`${newRow},${newCol}`); +function canPush(grid, pos, move) { + if (['<', '>'].includes(move)) { + const nextPos = getNext(getNext(pos, move), move); + if (grid[nextPos[0]][nextPos[1]] === '.') { + return true; } + if (grid[nextPos[0]][nextPos[1]] === '[' || grid[nextPos[0]][nextPos[1]] === ']') { + return canPush(grid, nextPos, move); + } + return false; } -}; -// Function to calculate the score of a trailhead -const calculateTrailheadScore = (startRow, startCol, map) => { - const rows = map.length; - const cols = map[0].length; - const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up - const reachableNines = new Set(); // Store unique positions of reachable 9s - const visited = new Set([`${startRow},${startCol}`]); // Initialize visited set with the trailhead + if (['^', 'v'].includes(move)) { + let left, right; + if (grid[pos[0]][pos[1]] === '[') { + left = pos; + right = [pos[0], pos[1] + 1]; + } else { + left = [pos[0], pos[1] - 1]; + right = pos; + } - // Start DFS to explore hiking paths from the trailhead - dfs(startRow, startCol, 0, visited, rows, cols, directions, map, reachableNines); + const nextLeft = getNext(left, move); + const nextRight = getNext(right, move); - return reachableNines.size; // Return the number of reachable '9' heights -}; + if (grid[nextLeft[0]][nextLeft[1]] === '#' || grid[nextRight[0]][nextRight[1]] === '#') { + return false; + } -// Function to find the sum of trailhead scores on the map -const findTrailheadScores = (map) => { - const rows = map.length; - const cols = map[0].length; - let totalScore = 0; + return (grid[nextLeft[0]][nextLeft[1]] === '.' || canPush(grid, nextLeft, move)) && + (grid[nextRight[0]][nextRight[1]] === '.' || canPush(grid, nextRight, move)); + } +} - // Loop through each position on the map to find trailheads (height 0) - for (let r = 0; r < rows; r++) { - for (let c = 0; c < cols; c++) { - if (map[r][c] === 0) { // Found a trailhead - totalScore += calculateTrailheadScore(r, c, map); // Add score from this trailhead - } +function push(grid, pos, move) { + if (['<', '>'].includes(move)) { + let j = pos[1]; + while (grid[pos[0]][j] !== '.') { + [, j] = getNext([pos[0], j], move); + } + if (j < pos[1]) { + grid[pos[0]].splice(j, pos[1] - j, ...grid[pos[0]].slice(j + 1, pos[1] + 1)); + } else { + grid[pos[0]].splice(pos[1] + 1, j - pos[1], ...grid[pos[0]].slice(pos[1], j)); } } - return totalScore; -}; - -// Main function to execute the program -const main = () => { - const map = parseInput('input.txt'); // Read and parse the map - const result = findTrailheadScores(map); // Calculate the sum of trailhead scores - console.log(`Sum of trailhead scores: ${result}`); // Output the result -}; + if (['^', 'v'].includes(move)) { + let left, right; + if (grid[pos[0]][pos[1]] === '[') { + left = pos; + right = [pos[0], pos[1] + 1]; + } else { + left = [pos[0], pos[1] - 1]; + right = pos; + } -main();",node:14 -2024,10,1,"--- Day 10: Hoof It --- + const nextLeft = getNext(left, move); + const nextRight = getNext(right, move); -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + if (grid[nextLeft[0]][nextLeft[1]] === '[') { + push(grid, nextLeft, move); + } else { + if (grid[nextLeft[0]][nextLeft[1]] === ']') { + push(grid, nextLeft, move); + } + if (grid[nextRight[0]][nextRight[1]] === '[') { + push(grid, nextRight, move); + } + } -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + grid[nextLeft[0]][nextLeft[1]] = '['; + grid[nextRight[0]][nextRight[1]] = ']'; + grid[left[0]][left[1]] = '.'; + grid[right[0]][right[1]] = '.'; + } +} -Perhaps you can help fill in the missing hiking trails? +function printGrid(grid) { + for (const line of grid) { + console.log(line.join('')); + } +} -The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: +let grid = []; +let moves = []; -0123 -1234 -8765 -9876 -Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). +const fs = require('fs'); +const input = fs.readFileSync('input.txt', 'utf8').split('\n'); -You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. +for (const line of input) { + if (line.startsWith('#')) { + let row = ''; + for (const c of line) { + row += getChars(c); + } + grid.push([...row]); + } else if (line !== '') { + moves.push(...line); + } +} -A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). +let robotPos; +for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + if (grid[i][j] === '@') { + robotPos = [i, j]; + break; + } + } + if (robotPos) break; +} -This trailhead has a score of 2: +for (const move of moves) { + const [nextI, nextJ] = getNext(robotPos, move); + if (grid[nextI][nextJ] === '.') { + grid[robotPos[0]][robotPos[1]] = '.'; + grid[nextI][nextJ] = '@'; + robotPos = [nextI, nextJ]; + } else if (grid[nextI][nextJ] === '[' || grid[nextI][nextJ] === ']') { + if (canPush(grid, [nextI, nextJ], move)) { + push(grid, [nextI, nextJ], move); + grid[robotPos[0]][robotPos[1]] = '.'; + grid[nextI][nextJ] = '@'; + robotPos = [nextI, nextJ]; + } + } +} -...0... -...1... -...2... -6543456 -7.....7 -8.....8 -9.....9 -(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) +let total = 0; +for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + if (grid[i][j] === '[') { + total += 100 * i + j; + } + } +} -This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: +console.log(total);",node:14 +2024,15,2,"--- Day 15: Warehouse Woes --- -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: +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? -10..9.. -2...8.. -3...7.. -4567654 -...8..3 -...9..2 -.....01 -Here's a larger example: +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! -The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"const fs = require('fs'); +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. -// Step 1: Parse the Input -const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n').map(line => line.split('').map(Number)); -const numRows = input.length; -const numCols = input[0].length; +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. -// Directions: up, down, left, right -const dirs = [ - [-1, 0], - [1, 0], - [0, -1], - [0, 1] -]; +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. -// Step 2: Identify Trailheads -const trailheads = []; -for (let i = 0; i < numRows; i++) { - for (let j = 0; j < numCols; j++) { - if (input[i][j] === 0) { - trailheads.push([i, j]); - } - } -} +For example: -// Step 3: DFS to find reachable 9s -function dfs(x, y, currentHeight, visited) { - if (currentHeight === 9) { - return new Set([[x, y].toString()]); - } - let reachable = new Set(); - for (const [dx, dy] of dirs) { - const nx = x + dx; - const ny = y + dy; - if ( - nx >= 0 && nx < numRows && - ny >= 0 && ny < numCols && - input[nx][ny] === currentHeight + 1 && - !visited.has([nx, ny].toString()) - ) { - visited.add([nx, ny].toString()); - const result = dfs(nx, ny, input[nx][ny], visited); - for (const pos of result) { - reachable.add(pos); - } - } - } - return reachable; -} +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## -// Step 4 & 5: Calculate Scores and Sum -let totalScore = 0; -for (const [i, j] of trailheads) { - const reachable9s = dfs(i, j, 0, new Set([`${i},${j}`])); - totalScore += reachable9s.size; -} +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. -console.log(totalScore);",node:14 -2024,10,1,"--- Day 10: Hoof It --- +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. +Here is a smaller example to get started: -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -Perhaps you can help fill in the missing hiking trails? +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: -The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -0123 -1234 -8765 -9876 -Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -This trailhead has a score of 2: +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -...0... -...1... -...2... -6543456 -7.....7 -8.....8 -9.....9 -(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -10..9.. -2...8.. -3...7.. -4567654 -...8..3 -...9..2 -.....01 -Here's a larger example: +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map?",587,"const fs = require(""fs""); +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## -// Constants -const DIRECTIONS = [ - [0, 1], // Right - [1, 0], // Down - [0, -1], // Left - [-1, 0], // Up -]; +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## -// Helper function to parse the input file into a 2D map -const parseInput = (filename) => { - const input = fs.readFileSync(filename, ""utf8"").trim(); - return input.split(""\n"").map((line) => line.split("""").map(Number)); -}; +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## -// Helper function to check if a position is valid on the map -const isValidPosition = (row, col, rows, cols) => { - return row >= 0 && row < rows && col >= 0 && col < cols; -}; +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## -// Depth-First Search (DFS) to find reachable 9s from a trailhead -const dfs = (row, col, currentHeight, map, visited, reachableNines) => { - const rows = map.length; - const cols = map[0].length; +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## - // If we reach a height of 9, add it to the reachableNines set - if (map[row][col] === 9) { - reachableNines.add(`${row},${col}`); - return; - } +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: - // Explore all four directions - for (const [dr, dc] of DIRECTIONS) { - const newRow = row + dr; - const newCol = col + dc; +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) - // Check if the new position is valid and not visited - if (isValidPosition(newRow, newCol, rows, cols) && !visited.has(`${newRow},${newCol}`)) { - // Ensure the height increases by exactly 1 - if (map[newRow][newCol] === currentHeight + 1) { - visited.add(`${newRow},${newCol}`); - dfs(newRow, newCol, currentHeight + 1, map, visited, reachableNines); - visited.delete(`${newRow},${newCol}`); - } - } - } -}; +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. -// Calculate the score for a single trailhead -const calculateTrailheadScore = (startRow, startCol, map) => { - const reachableNines = new Set(); // Track unique positions of reachable 9s - const visited = new Set([`${startRow},${startCol}`]); // Track visited positions +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. - // Perform DFS to find all reachable 9s - dfs(startRow, startCol, 0, map, visited, reachableNines); +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? - return reachableNines.size; // The score is the number of unique reachable 9s -}; +Your puzzle answer was 1499739. -// Find the sum of scores for all trailheads on the map -const findTrailheadScores = (map) => { - const rows = map.length; - const cols = map[0].length; - let totalScore = 0; +--- Part Two --- - // Iterate through the map to find all trailheads (height 0) - for (let r = 0; r < rows; r++) { - for (let c = 0; c < cols; c++) { - if (map[r][c] === 0) { - const score = calculateTrailheadScore(r, c, map); - totalScore += score; - } - } - } +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. - return totalScore; -}; +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. -// Main function to execute the program -const main = () => { - try { - const map = parseInput(""input.txt""); // Parse the input file - const result = findTrailheadScores(map); // Calculate the total score - console.log(`Sum of trailhead scores: ${result}`); - } catch (error) { - console.error(""Error:"", error.message); - } -}; +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: -// Run the program -main();",node:14 -2024,10,2,"--- Day 10: Hoof It --- +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. +The larger example from before would now look like this: -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: -Perhaps you can help fill in the missing hiking trails? +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### -The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: +': [0, 1], + 'v': [1, 0], + '<': [0, -1] + }; + + getNext(pos, move) { + const [dx, dy] = WarehouseSolver.MOVE_DICT[move]; + return [pos[0] + dx, pos[1] + dy]; + } + + // Grid character expansion + getChars(c) { + switch (c) { + case '@': return '@.'; + case 'O': return '[]'; + default: return c + c; + } + } + + // Parsing and grid setup + parseInput(input) { + for (const line of input.split('\n')) { + if (line.startsWith('#')) { + const row = [...line].map(c => this.getChars(c)).join(''); + this.grid.push([...row]); + } else if (line.trim() !== '') { + this.moves.push(...line.trim()); + } + } + this.findRobot(); + } -.....0. .....0. .....0. -..4321. .....1. .....1. -..5.... .....2. .....2. -..6.... ..6543. .....3. -..7.... ..7.... .....4. -..8.... ..8.... ..8765. -..9.... ..9.... ..9.... -Here is a map containing a single trailhead with rating 13: + findRobot() { + for (let i = 0; i < this.grid.length; i++) { + for (let j = 0; j < this.grid[i].length; j++) { + if (this.grid[i][j] === '@') { + this.robotPos = [i, j]; + return; + } + } + } + } -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + // Movement validation + canPush(pos, move) { + if (['<', '>'].includes(move)) { + return this.canPushHorizontal(pos, move); + } + return this.canPushVertical(pos, move); + } -012345 -123456 -234567 -345678 -4.6789 -56789. -Here's the larger example from before: + canPushHorizontal(pos, move) { + const nextPos = this.getNext(this.getNext(pos, move), move); + const nextChar = this.grid[nextPos[0]][nextPos[1]]; + + if (nextChar === '.') return true; + if (['[', ']'].includes(nextChar)) { + return this.canPush(nextPos, move); + } + return false; + } -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + canPushVertical(pos, move) { + const [left, right] = this.getBoxEdges(pos); + const nextLeft = this.getNext(left, move); + const nextRight = this.getNext(right, move); -You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"const fs = require(""fs""); -const inputText = ""./input.txt""; + if (this.grid[nextLeft[0]][nextLeft[1]] === '#' || + this.grid[nextRight[0]][nextRight[1]] === '#') { + return false; + } -fs.readFile(inputText, ""utf8"", (err, data) => { - if (err) { - console.error('Error reading file:', err); - return; - } - - console.log(""Part 1:"", getTotalValidTrails(data)); - console.log(""Part 2:"", getTotalValidTrails(data, true)); -}); + return (this.grid[nextLeft[0]][nextLeft[1]] === '.' || this.canPush(nextLeft, move)) && + (this.grid[nextRight[0]][nextRight[1]] === '.' || this.canPush(nextRight, move)); + } -const getZeroLocations = data => { - const zeroLocations = []; - for (let i = 0; i < data.length; i++) { - const line = data[i]; - for (let j = 0; j < line.length; j++) { - const item = line[j]; - if (item === 0) { - zeroLocations.push([i, j]); - } + getBoxEdges(pos) { + return this.grid[pos[0]][pos[1]] === '[' + ? [pos, [pos[0], pos[1] + 1]] + : [[pos[0], pos[1] - 1], pos]; } - } - return zeroLocations; -} -const getValidTrails = (mapArr, startLocation, cumulative) => { - const directions = [[-1, 0], [0, -1], [1, 0],[0, 1]]; - const visited = new Set(); - let validTrails = 0; - const queue = [startLocation]; - if (!cumulative) visited.add(`${startLocation[0]}, ${startLocation[1]}`) + // Pushing mechanics + push(pos, move) { + return ['<', '>'].includes(move) + ? this.pushHorizontal(pos, move) + : this.pushVertical(pos, move); + } - while (queue.length > 0) { - const [currX, currY] = queue.shift(); - if (mapArr[currX][currY] === 9) { - validTrails++; + pushHorizontal(pos, move) { + let j = pos[1]; + while (this.grid[pos[0]][j] !== '.') { + [, j] = this.getNext([pos[0], j], move); + } + + const slice = j < pos[1] + ? this.grid[pos[0]].slice(j + 1, pos[1] + 1) + : this.grid[pos[0]].slice(pos[1], j); + + this.grid[pos[0]].splice( + j < pos[1] ? j : pos[1] + 1, + Math.abs(j - pos[1]), + ...slice + ); } - for (let [dx, dy] of directions) { - const nextX = currX + dx; - const nextY = currY + dy; - - // Check if next coord is within the map - if (nextX >= 0 && nextY >= 0 && nextX < mapArr.length && nextY < mapArr[0].length) { - if (mapArr[nextX][nextY] !== (mapArr[currX][currY] + 1)) continue; - const nextCoordStr = `${nextX}, ${nextY}`; - // Part2 is cumulative, part1 requires that this coord has not yet been visited - if (cumulative || !visited.has(nextCoordStr)) { - queue.push([nextX, nextY]); - visited.add(nextCoordStr); + pushVertical(pos, move) { + const [left, right] = this.getBoxEdges(pos); + const nextLeft = this.getNext(left, move); + const nextRight = this.getNext(right, move); + + // Recursive push for existing boxes + if (['[', ']'].includes(this.grid[nextLeft[0]][nextLeft[1]])) { + this.push(nextLeft, move); } - } + if (['[', ']'].includes(this.grid[nextRight[0]][nextRight[1]])) { + this.push(nextRight, move); + } + + // Update grid + this.grid[nextLeft[0]][nextLeft[1]] = '['; + this.grid[nextRight[0]][nextRight[1]] = ']'; + this.grid[left[0]][left[1]] = '.'; + this.grid[right[0]][right[1]] = '.'; } - } - return validTrails; -} -const getTotalValidTrails = (data, cumulative) => { - let totalValidTrails = 0; - const mapArr = data.split(""\n"").map(line => line.split("""").map(Number)); - const zeros = getZeroLocations(mapArr); + // Main solving method + solve(input) { + this.parseInput(input); - for (let zero of zeros) { - const validTrails = getValidTrails(mapArr, zero, cumulative); - totalValidTrails += validTrails; - } - return totalValidTrails; -}",node:14 -2024,10,2,"--- Day 10: Hoof It --- + for (const move of this.moves) { + const [nextI, nextJ] = this.getNext(this.robotPos, move); + + if (this.grid[nextI][nextJ] === '.') { + this.moveRobot(nextI, nextJ); + } else if (['[', ']'].includes(this.grid[nextI][nextJ])) { + if (this.canPush([nextI, nextJ], move)) { + this.push([nextI, nextJ], move); + this.moveRobot(nextI, nextJ); + } + } + } -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. + return this.calculateTotal(); + } -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. + moveRobot(nextI, nextJ) { + this.grid[this.robotPos[0]][this.robotPos[1]] = '.'; + this.grid[nextI][nextJ] = '@'; + this.robotPos = [nextI, nextJ]; + } -Perhaps you can help fill in the missing hiking trails? + calculateTotal() { + let total = 0; + for (let i = 0; i < this.grid.length; i++) { + for (let j = 0; j < this.grid[i].length; j++) { + if (this.grid[i][j] === '[') { + total += 100 * i + j; + } + } + } + return total; + } -The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: + // Optional debug method + printGrid() { + console.log(this.grid.map(row => row.join('')).join('\n')); + } +} -0123 -1234 -8765 -9876 -Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). +// Usage +const fs = require('fs'); +const input = fs.readFileSync('input.txt', 'utf8'); +const solver = new WarehouseSolver(); +console.log(solver.solve(input));",node:14 +2024,15,2,"--- Day 15: Warehouse Woes --- -You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. +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? -A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. -This trailhead has a score of 2: +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! -...0... -...1... -...2... -6543456 -7.....7 -8.....8 -9.....9 -(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. -This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. -10..9.. -2...8.. -3...7.. -4567654 -...8..3 -...9..2 -.....01 -Here's a larger example: +For example: -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## -The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. -Your puzzle answer was 587. +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) ---- Part Two --- +Here is a smaller example to get started: -The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: -.....0. -..4321. -..5..2. -..6543. -..7..4. -..8765. -..9.... -The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -.....0. .....0. .....0. -..4321. .....1. .....1. -..5.... .....2. .....2. -..6.... ..6543. .....3. -..7.... ..7.... .....4. -..8.... ..8.... ..8765. -..9.... ..9.... ..9.... -Here is a map containing a single trailhead with rating 13: +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -012345 -123456 -234567 -345678 -4.6789 -56789. -Here's the larger example from before: +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## -You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"const fs = require('fs'); +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## -class HikingTrails { - constructor(grid) { - this.grid = grid; - this.rows = grid.length; - this.cols = grid[0].length; - this.directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up - } +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## - findTrailheadRatings() { - let totalRating = 0; - - // Find all trailheads (height 0) - for (let r = 0; r < this.rows; r++) { - for (let c = 0; c < this.cols; c++) { - if (this.grid[r][c] === 0) { - const rating = this.calculateTrailheadRating(r, c); - totalRating += rating; - } - } - } - - return totalRating; - } +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## - calculateTrailheadRating(startRow, startCol) { - const paths = new Set(); - const visited = new Set(); +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## - const buildPath = (path) => { - return path.join(','); - }; +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## - const dfs = (row, col, currentHeight, currentPath) => { - // If we reached height 9, we found a complete path - if (this.grid[row][col] === 9) { - paths.add(buildPath(currentPath)); - return; - } +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## - // Try all directions - for (const [dr, dc] of this.directions) { - const newRow = row + dr; - const newCol = col + dc; - const newPos = `${newRow},${newCol}`; +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## - if (this.isValidMove(newRow, newCol) && - !visited.has(newPos) && - this.grid[newRow][newCol] === currentHeight + 1) { - - visited.add(newPos); - currentPath.push(newPos); - - dfs(newRow, newCol, currentHeight + 1, currentPath); - - visited.delete(newPos); - currentPath.pop(); - } - } - }; +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## - // Start DFS from the trailhead - const startPos = `${startRow},${startCol}`; - visited.add(startPos); - dfs(startRow, startCol, 0, [startPos]); +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: - return paths.size; - } +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) - isValidMove(row, col) { - return row >= 0 && row < this.rows && col >= 0 && col < this.cols; - } -} +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. -function parseInput(filename) { - try { - const input = fs.readFileSync(filename, 'utf8').trim(); - return input.split('\n').map(line => - line.split('').map(Number) - ); - } catch (error) { - console.error('Error reading input file:', error); - process.exit(1); - } -} +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. -function solve(filename) { - const grid = parseInput(filename); - const hikingTrails = new HikingTrails(grid); - return hikingTrails.findTrailheadRatings(); -} +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? -// Execute solution -try { - const result = solve('input.txt'); - console.log(`Sum of trailhead ratings: ${result}`); -} catch (error) { - console.error('Error:', error); - process.exit(1); -}",node:14 -2024,10,2,"--- Day 10: Hoof It --- +Your puzzle answer was 1499739. -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. +--- Part Two --- -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. -Perhaps you can help fill in the missing hiking trails? +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. -The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: -0123 -1234 -8765 -9876 -Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) -You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. +The larger example from before would now look like this: -A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: -This trailhead has a score of 2: +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### -...0... -...1... -...2... -6543456 -7.....7 -8.....8 -9.....9 -(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) +': [0, 1], + 'v': [1, 0], + '<': [0, -1] + }, + + init: function() { + this.grid = []; + this.moves = []; + this.robotPos = null; + }, + + getNext: function(pos, move) { + const [dx, dy] = WarehouseSolver.MOVE_DICT[move]; + return [pos[0] + dx, pos[1] + dy]; + }, + + getChars: function(c) { + switch (c) { + case '@': return '@.'; + case 'O': return '[]'; + default: return c + c; + } + }, + + parseInput: function(input) { + input.split('\n').forEach(line => { + if (line.startsWith('#')) { + const row = [...line].map(c => this.getChars(c)).join(''); + this.grid.push([...row]); + } else if (line.trim() !== '') { + this.moves.push(...line.trim()); + } + }); + this.findRobot(); + }, + + findRobot: function() { + for (let i = 0; i < this.grid.length; i++) { + for (let j = 0; j < this.grid[i].length; j++) { + if (this.grid[i][j] === '@') { + this.robotPos = [i, j]; + return; + } + } + } + }, -class HikingTrails { - constructor(grid) { - this.grid = grid; - this.rows = grid.length; - this.cols = grid[0].length; - this.directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // right, down, left, up - } + canPush: function(pos, move) { + return ['<', '>'].includes(move) ? this.canPushHorizontal(pos, move) : this.canPushVertical(pos, move); + }, - // Main function to compute the sum of trailhead ratings - calculateTotalTrailheadRatings() { - let totalRating = 0; + canPushHorizontal: function(pos, move) { + const nextPos = this.getNext(this.getNext(pos, move), move); + const nextChar = this.grid[nextPos[0]][nextPos[1]]; + + if (nextChar === '.') return true; + if (['[', ']'].includes(nextChar)) { + return this.canPush(nextPos, move); + } + return false; + }, + + canPushVertical: function(pos, move) { + const [left, right] = this.getBoxEdges(pos); + const nextLeft = this.getNext(left, move); + const nextRight = this.getNext(right, move); + + if (this.grid[nextLeft[0]][nextLeft[1]] === '#' || + this.grid[nextRight[0]][nextRight[1]] === '#') { + return false; + } - for (let r = 0; r < this.rows; r++) { - for (let c = 0; c < this.cols; c++) { - if (this.grid[r][c] === 0) { // Found a trailhead - totalRating += this.calculateTrailheadRating(r, c); - } - } + return (this.grid[nextLeft[0]][nextLeft[1]] === '.' || this.canPush(nextLeft, move)) && + (this.grid[nextRight[0]][nextRight[1]] === '.' || this.canPush(nextRight, move)); + }, + + getBoxEdges: function(pos) { + return this.grid[pos[0]][pos[1]] === '[' + ? [pos, [pos[0], pos[1] + 1]] + : [[pos[0], pos[1] - 1], pos]; + }, + + push: function(pos, move) { + return ['<', '>'].includes(move) + ? this.pushHorizontal(pos, move) + : this.pushVertical(pos, move); + }, + + pushHorizontal: function(pos, move) { + let j = pos[1]; + while (this.grid[pos[0]][j] !== '.') { + [, j] = this.getNext([pos[0], j], move); } + + const slice = j < pos[1] + ? this.grid[pos[0]].slice(j + 1, pos[1] + 1) + : this.grid[pos[0]].slice(pos[1], j); + + this.grid[pos[0]].splice( + j < pos[1] ? j : pos[1] + 1, + Math.abs(j - pos[1]), + ...slice + ); + }, - return totalRating; - } + pushVertical: function(pos, move) { + const [left, right] = this.getBoxEdges(pos); + const nextLeft = this.getNext(left, move); + const nextRight = this.getNext(right, move); - // Calculate the rating for a specific trailhead (height 0) - calculateTrailheadRating(startRow, startCol) { - const paths = new Set(); // Store unique paths - const visited = new Set(); // Store visited positions + if (['[', ']'].includes(this.grid[nextLeft[0]][nextLeft[1]])) { + this.push(nextLeft, move); + } + if (['[', ']'].includes(this.grid[nextRight[0]][nextRight[1]])) { + this.push(nextRight, move); + } - const dfs = (row, col, currentHeight, currentPath) => { - // If we reached height 9, we found a valid path - if (this.grid[row][col] === 9) { - paths.add(currentPath.join(',')); // Store path as a string - return; + this.grid[nextLeft[0]][nextLeft[1]] = '['; + this.grid[nextRight[0]][nextRight[1]] = ']'; + this.grid[left[0]][left[1]] = '.'; + this.grid[right[0]][right[1]] = '.'; + }, + + moveRobot: function(nextI, nextJ) { + this.grid[this.robotPos[0]][this.robotPos[1]] = '.'; + this.grid[nextI][nextJ] = '@'; + this.robotPos = [nextI, nextJ]; + }, + + calculateTotal: function() { + let total = 0; + for (let i = 0; i < this.grid.length; i++) { + for (let j = 0; j < this.grid[i].length; j++) { + if (this.grid[i][j] === '[') { + total += 100 * i + j; + } } + } + return total; + }, - // Explore all four possible directions (right, down, left, up) - for (const [dr, dc] of this.directions) { - const newRow = row + dr; - const newCol = col + dc; - const newPos = `${newRow},${newCol}`; + solve: function(input) { + this.init(); + this.parseInput(input); - if (this.isValidMove(newRow, newCol) && - !visited.has(newPos) && - this.grid[newRow][newCol] === currentHeight + 1) { - - visited.add(newPos); - currentPath.push(newPos); - - // Continue DFS - dfs(newRow, newCol, currentHeight + 1, currentPath); - - visited.delete(newPos); // Backtrack - currentPath.pop(); + this.moves.forEach(move => { + const [nextI, nextJ] = this.getNext(this.robotPos, move); + + if (this.grid[nextI][nextJ] === '.') { + this.moveRobot(nextI, nextJ); + } else if (['[', ']'].includes(this.grid[nextI][nextJ])) { + if (this.canPush([nextI, nextJ], move)) { + this.push([nextI, nextJ], move); + this.moveRobot(nextI, nextJ); } } - }; + }); - // Start DFS from the trailhead - const startPos = `${startRow},${startCol}`; - visited.add(startPos); - dfs(startRow, startCol, 0, [startPos]); + return this.calculateTotal(); + }, - return paths.size; // Return number of unique paths to height 9 + printGrid: function() { + console.log(this.grid.map(row => row.join('')).join('\n')); } +}; - // Check if a position is within bounds - isValidMove(row, col) { - return row >= 0 && row < this.rows && col >= 0 && col < this.cols; - } -} +// Usage +const fs = require('fs'); +const input = fs.readFileSync('input.txt', 'utf8'); +console.log(WarehouseSolver.solve(input));",node:14 +2024,15,2,"--- Day 15: Warehouse Woes --- -// Read and parse the input file into a 2D grid -const parseInput = (filename) => { - try { - const input = fs.readFileSync(filename, 'utf8').trim(); - return input.split('\n').map(line => - line.split('').map(Number) // Convert each character to a number - ); - } catch (error) { - console.error('Error reading input file:', error); - process.exit(1); - } -}; +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? -// Solve the problem and return the result -const solve = (filename) => { - const grid = parseInput(filename); - const hikingTrails = new HikingTrails(grid); - return hikingTrails.calculateTotalTrailheadRatings(); -}; +You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help. -// Main execution -try { - const result = solve('input.txt'); - console.log(`Sum of trailhead ratings: ${result}`); -} catch (error) { - console.error('Error:', error); - process.exit(1); -}",node:14 -2024,10,2,"--- Day 10: Hoof It --- +Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots! -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. +These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies. -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. +Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option. -Perhaps you can help fill in the missing hiking trails? +The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict. -The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: +For example: -0123 -1234 -8765 -9876 -Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). +########## +#..O..O.O# +#......O.# +#.OO..O.O# +#..O@..O.# +#O#..O...# +#O..O..O.# +#.OO.O.OO# +#....O...# +########## -You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. +^v>^vv^v>v<>v^v<<><>>v^v^>^<<<><^ +vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<^<^^>>>^<>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^v^^<^^vv< +<>^^^^>>>v^<>vvv^>^^^vv^^>v<^^^^v<>^>vvvv><>>v^<<^^^^^ +^><^><>>><>^^<<^^v>>><^^>v>>>^v><>^v><<<>vvvv>^<><<>^>< +^>><>^v<><^vvv<^^<><^v<<<><<<^^<^>>^<<<^>>^v^>>^v>vv>^<<^v<>><<><<>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^ +<><^^>^^^<>^vv<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<> +^^>vv<^v^v^<>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<>< +v^^>>><<^^<>>^v^v^<<>^<^v^v><^<<<><<^vv>>v>v^<<^ +As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you. + +The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.) + +Here is a smaller example to get started: + +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +<^^>>>vv>v<< +Were the robot to attempt the given sequence of moves, it would push around the boxes as follows: + +Initial state: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move <: +######## +#..O.O.# +##@.O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move ^: +######## +#.@O.O.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#..@OO.# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move >: +######## +#...@OO# +##..O..# +#...O..# +#.#.O..# +#...O..# +#......# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##..@..# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move <: +######## +#....OO# +##.@...# +#...O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move v: +######## +#....OO# +##.....# +#..@O..# +#.#.O..# +#...O..# +#...O..# +######## + +Move >: +######## +#....OO# +##.....# +#...@O.# +#.#.O..# +#...O..# +#...O..# +######## -A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). +Move >: +######## +#....OO# +##.....# +#....@O# +#.#.O..# +#...O..# +#...O..# +######## -This trailhead has a score of 2: +Move v: +######## +#....OO# +##.....# +#.....O# +#.#.O@.# +#...O..# +#...O..# +######## -...0... -...1... -...2... -6543456 -7.....7 -8.....8 -9.....9 -(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## -This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: +Move <: +######## +#....OO# +##.....# +#.....O# +#.#O@..# +#...O..# +#...O..# +######## +The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this: -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: +########## +#.O.O.OOO# +#........# +#OO......# +#OO@.....# +#O#.....O# +#O.....OO# +#O.....OO# +#OO....OO# +########## +The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.) -10..9.. -2...8.. -3...7.. -4567654 -...8..3 -...9..2 -.....01 -Here's a larger example: +So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104. -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. +####### +#...O.. +#...... +The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028. -The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? +Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates? -Your puzzle answer was 587. +Your puzzle answer was 1499739. --- Part Two --- -The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. +The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning. -The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: +This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change. -.....0. -..4321. -..5..2. -..6543. -..7..4. -..8765. -..9.... -The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: +To get the wider warehouse's map, start with your original map and, for each tile, make the following changes: -.....0. .....0. .....0. -..4321. .....1. .....1. -..5.... .....2. .....2. -..6.... ..6543. .....3. -..7.... ..7.... .....4. -..8.... ..8.... ..8765. -..9.... ..9.... ..9.... -Here is a map containing a single trailhead with rating 13: +If the tile is #, the new map contains ## instead. +If the tile is O, the new map contains [] instead. +If the tile is ., the new map contains .. instead. +If the tile is @, the new map contains @. instead. +This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.) -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): +The larger example from before would now look like this: -012345 -123456 -234567 -345678 -4.6789 -56789. -Here's the larger example from before: +#################### +##....[]....[]..[]## +##............[]..## +##..[][]....[]..[]## +##....[]@.....[]..## +##[]##....[]......## +##[]....[]....[]..## +##..[][]..[]..[][]## +##........[]......## +#################### +Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation: -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. +####### +#...#.# +#.....# +#..OO@# +#..O..# +#.....# +####### -You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"const fs = require('fs'); -const {log} = require('console'); += 0 && nextR >= 0 && nextC < lines[0].length && nextR < lines.length; -} +Move <: +############## +##......##..## +##..........## +##...[][]...## +##....[]....## +##......@...## +############## -function getScore(trailhead, distinct) { - let score = []; - let queue = directions.map(d => [...trailhead, trailhead[0] + d[0], trailhead[1] + d[1]]); - while (queue.length > 0) { - let [c, r, nextC, nextR] = queue.shift(); - if (isInBounds(nextC, nextR) && parseInt(lines[nextR][nextC]) - parseInt(lines[r][c]) === 1) { - if (lines[nextR][nextC] === '9') { - score.push(`${nextC}-${nextR}`); - } else { - directions.forEach(d => queue.push([nextC, nextR, nextC + d[0], nextR + d[1]])) - } - } - } - if (distinct) { - return score.length; - } else { - return new Set(score).size; - } -} +Move <: +############## +##......##..## +##..........## +##...[][]...## +##....[]....## +##.....@....## +############## + +Move ^: +############## +##......##..## +##...[][]...## +##....[]....## +##.....@....## +##..........## +############## -let part1 = 0; -for (let trailhead of trailheads) { - part1 += getScore(trailhead, false); -} -log(part1); +Move ^: +############## +##......##..## +##...[][]...## +##....[]....## +##.....@....## +##..........## +############## -let part2 = 0; -for (let trailhead of trailheads) { - part2 += getScore(trailhead, true); -} -log(part2);",node:14 -2024,10,2,"--- Day 10: Hoof It --- +Move <: +############## +##......##..## +##...[][]...## +##....[]....## +##....@.....## +##..........## +############## -You all arrive at a Lava Production Facility on a floating island in the sky. As the others begin to search the massive industrial complex, you feel a small nose boop your leg and look down to discover a reindeer wearing a hard hat. +Move <: +############## +##......##..## +##...[][]...## +##....[]....## +##...@......## +##..........## +############## -The reindeer is holding a book titled ""Lava Island Hiking Guide"". However, when you open the book, you discover that most of it seems to have been scorched by lava! As you're about to ask how you can help, the reindeer brings you a blank topographic map of the surrounding area (your puzzle input) and looks up at you excitedly. +Move ^: +############## +##......##..## +##...[][]...## +##...@[]....## +##..........## +##..........## +############## -Perhaps you can help fill in the missing hiking trails? +Move ^: +############## +##...[].##..## +##...@.[]...## +##....[]....## +##..........## +##..........## +############## +This warehouse also uses GPS to locate the boxes. For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question. So, the box shown below has a distance of 1 from the top edge of the map and 5 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 5 = 105. -The topographic map indicates the height at each position using a scale from 0 (lowest) to 9 (highest). For example: +########## +##...[]... +##........ +In the scaled-up version of the larger example from above, after the robot has finished all of its moves, the warehouse would look like this: -0123 -1234 -8765 -9876 -Based on un-scorched scraps of the book, you determine that a good hiking trail is as long as possible and has an even, gradual, uphill slope. For all practical purposes, this means that a hiking trail is any path that starts at height 0, ends at height 9, and always increases by a height of exactly 1 at each step. Hiking trails never include diagonal steps - only up, down, left, or right (from the perspective of the map). +#################### +##[].......[].[][]## +##[]...........[].## +##[]........[][][]## +##[]......[]....[]## +##..##......[]....## +##..[]............## +##..@......[].[][]## +##......[][]..[]..## +#################### +The sum of these boxes' GPS coordinates is 9021. -You look up from the map and notice that the reindeer has helpfully begun to construct a small pile of pencils, markers, rulers, compasses, stickers, and other equipment you might need to update the map with hiking trails. +Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes' final GPS coordinates?",1522215,"class GridMovement { + static MOVES = { + '^': [-1, 0], + '>': [0, 1], + 'v': [1, 0], + '<': [0, -1] + }; -A trailhead is any position that starts one or more hiking trails - here, these positions will always have height 0. Assembling more fragments of pages, you establish that a trailhead's score is the number of 9-height positions reachable from that trailhead via a hiking trail. In the above example, the single trailhead in the top left corner has a score of 1 because it can reach a single 9 (the one in the bottom left). + static getNextPosition(pos, move) { + const [dx, dy] = this.MOVES[move]; + return [pos[0] + dx, pos[1] + dy]; + } +} -This trailhead has a score of 2: +class GridParser { + static parseCharacter(c) { + switch (c) { + case '@': return '@.'; + case 'O': return '[]'; + default: return c + c; + } + } -...0... -...1... -...2... -6543456 -7.....7 -8.....8 -9.....9 -(The positions marked . are impassable tiles to simplify these examples; they do not appear on your actual topographic map.) + static parse(input) { + const grid = []; + const moves = []; -This trailhead has a score of 4 because every 9 is reachable via a hiking trail except the one immediately to the left of the trailhead: + input.split('\n').forEach(line => { + if (line.startsWith('#')) { + const row = [...line].map(c => GridParser.parseCharacter(c)).join(''); + grid.push([...row]); + } else if (line.trim()) { + moves.push(...line.trim()); + } + }); -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This topographic map contains two trailheads; the trailhead at the top has a score of 1, while the trailhead at the bottom has a score of 2: + return { grid, moves }; + } +} -10..9.. -2...8.. -3...7.. -4567654 -...8..3 -...9..2 -.....01 -Here's a larger example: +class WarehouseSolver { + constructor() { + this.grid = []; + this.moves = []; + this.robotPos = null; + } -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -This larger example has 9 trailheads. Considering the trailheads in reading order, they have scores of 5, 6, 5, 3, 1, 3, 5, 3, and 5. Adding these scores together, the sum of the scores of all trailheads is 36. + solve(input) { + const { grid, moves } = GridParser.parse(input); + this.grid = grid; + this.moves = moves; + this.findRobot(); -The reindeer gleefully carries over a protractor and adds it to the pile. What is the sum of the scores of all trailheads on your topographic map? + this.executeMoves(); + return this.calculateTotal(); + } -Your puzzle answer was 587. + findRobot() { + for (let i = 0; i < this.grid.length; i++) { + for (let j = 0; j < this.grid[i].length; j++) { + if (this.grid[i][j] === '@') { + this.robotPos = [i, j]; + return; + } + } + } + } ---- Part Two --- + executeMoves() { + this.moves.forEach(move => { + const [nextI, nextJ] = GridMovement.getNextPosition(this.robotPos, move); + + if (this.grid[nextI][nextJ] === '.') { + this.moveRobot(nextI, nextJ); + } else if (['[', ']'].includes(this.grid[nextI][nextJ])) { + if (this.canPush([nextI, nextJ], move)) { + this.push([nextI, nextJ], move); + this.moveRobot(nextI, nextJ); + } + } + }); + } -The reindeer spends a few minutes reviewing your hiking trail map before realizing something, disappearing for a few minutes, and finally returning with yet another slightly-charred piece of paper. + canPush(pos, move) { + return ['<', '>'].includes(move) + ? this.canPushHorizontal(pos, move) + : this.canPushVertical(pos, move); + } -The paper describes a second way to measure a trailhead called its rating. A trailhead's rating is the number of distinct hiking trails which begin at that trailhead. For example: + canPushHorizontal(pos, move) { + const nextPos = GridMovement.getNextPosition( + GridMovement.getNextPosition(pos, move), + move + ); + const nextChar = this.grid[nextPos[0]][nextPos[1]]; + + if (nextChar === '.') return true; + if (['[', ']'].includes(nextChar)) { + return this.canPush(nextPos, move); + } + return false; + } -.....0. -..4321. -..5..2. -..6543. -..7..4. -..8765. -..9.... -The above map has a single trailhead; its rating is 3 because there are exactly three distinct hiking trails which begin at that position: + canPushVertical(pos, move) { + const [left, right] = this.getBoxEdges(pos); + const nextLeft = GridMovement.getNextPosition(left, move); + const nextRight = GridMovement.getNextPosition(right, move); -.....0. .....0. .....0. -..4321. .....1. .....1. -..5.... .....2. .....2. -..6.... ..6543. .....3. -..7.... ..7.... .....4. -..8.... ..8.... ..8765. -..9.... ..9.... ..9.... -Here is a map containing a single trailhead with rating 13: + if (this.grid[nextLeft[0]][nextLeft[1]] === '#' || + this.grid[nextRight[0]][nextRight[1]] === '#') { + return false; + } -..90..9 -...1.98 -...2..7 -6543456 -765.987 -876.... -987.... -This map contains a single trailhead with rating 227 (because there are 121 distinct hiking trails that lead to the 9 on the right edge and 106 that lead to the 9 on the bottom edge): + return (this.grid[nextLeft[0]][nextLeft[1]] === '.' || this.canPush(nextLeft, move)) && + (this.grid[nextRight[0]][nextRight[1]] === '.' || this.canPush(nextRight, move)); + } -012345 -123456 -234567 -345678 -4.6789 -56789. -Here's the larger example from before: + getBoxEdges(pos) { + return this.grid[pos[0]][pos[1]] === '[' + ? [pos, [pos[0], pos[1] + 1]] + : [[pos[0], pos[1] - 1], pos]; + } -89010123 -78121874 -87430965 -96549874 -45678903 -32019012 -01329801 -10456732 -Considering its trailheads in reading order, they have ratings of 20, 24, 10, 4, 1, 4, 5, 8, and 5. The sum of all trailhead ratings in this larger example topographic map is 81. + push(pos, move) { + return ['<', '>'].includes(move) + ? this.pushHorizontal(pos, move) + : this.pushVertical(pos, move); + } -You're not sure how, but the reindeer seems to have crafted some tiny flags out of toothpicks and bits of paper and is using them to mark trailheads on your topographic map. What is the sum of the ratings of all trailheads?",1340,"const fs = require('fs'); + pushHorizontal(pos, move) { + let j = pos[1]; + while (this.grid[pos[0]][j] !== '.') { + [, j] = GridMovement.getNextPosition([pos[0], j], move); + } + + const slice = j < pos[1] + ? this.grid[pos[0]].slice(j + 1, pos[1] + 1) + : this.grid[pos[0]].slice(pos[1], j); + + this.grid[pos[0]].splice( + j < pos[1] ? j : pos[1] + 1, + Math.abs(j - pos[1]), + ...slice + ); + } -// Step 1: Parse the Input -const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n').map(line => line.split('').map(Number)); -const numRows = input.length; -const numCols = input[0].length; + pushVertical(pos, move) { + const [left, right] = this.getBoxEdges(pos); + const nextLeft = GridMovement.getNextPosition(left, move); + const nextRight = GridMovement.getNextPosition(right, move); -// Directions: up, down, left, right -const dirs = [ - [-1, 0], - [1, 0], - [0, -1], - [0, 1] -]; + if (['[', ']'].includes(this.grid[nextLeft[0]][nextLeft[1]])) { + this.push(nextLeft, move); + } + if (['[', ']'].includes(this.grid[nextRight[0]][nextRight[1]])) { + this.push(nextRight, move); + } -// Step 2: Identify Trailheads -const trailheads = []; -for (let i = 0; i < numRows; i++) { - for (let j = 0; j < numCols; j++) { - if (input[i][j] === 0) { - trailheads.push([i, j]); + this.grid[nextLeft[0]][nextLeft[1]] = '['; + this.grid[nextRight[0]][nextRight[1]] = ']'; + this.grid[left[0]][left[1]] = '.'; + this.grid[right[0]][right[1]] = '.'; } - } -} -// Step 3: Memoization Map -const memo = Array.from({ length: numRows }, () => Array(numCols).fill(null)); + moveRobot(nextI, nextJ) { + this.grid[this.robotPos[0]][this.robotPos[1]] = '.'; + this.grid[nextI][nextJ] = '@'; + this.robotPos = [nextI, nextJ]; + } -// Step 4: DFS to count distinct trails -function countTrails(x, y) { - if (input[x][y] === 9) { - return 1; - } - if (memo[x][y] !== null) { - return memo[x][y]; - } - let totalPaths = 0; - for (const [dx, dy] of dirs) { - const nx = x + dx; - const ny = y + dy; - if ( - nx >= 0 && nx < numRows && - ny >= 0 && ny < numCols && - input[nx][ny] === input[x][y] + 1 - ) { - totalPaths += countTrails(nx, ny); + calculateTotal() { + let total = 0; + for (let i = 0; i < this.grid.length; i++) { + for (let j = 0; j < this.grid[i].length; j++) { + if (this.grid[i][j] === '[') { + total += 100 * i + j; + } + } + } + return total; } - } - memo[x][y] = totalPaths; - return totalPaths; -} -// Step 5 & 6: Calculate Ratings and Sum -let totalRating = 0; -for (const [i, j] of trailheads) { - totalRating += countTrails(i, j); + printGrid() { + console.log(this.grid.map(row => row.join('')).join('\n')); + } } -console.log(totalRating);",node:14 \ No newline at end of file +// Usage +const fs = require('fs'); +const solver = new WarehouseSolver(); +const input = fs.readFileSync('input.txt', 'utf8'); +console.log(solver.solve(input));",node:14 \ No newline at end of file