diff --git "a/aoc.csv" "b/aoc.csv" --- "a/aoc.csv" +++ "b/aoc.csv" @@ -62541,4 +62541,14987 @@ class WarehouseSolver { 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 +console.log(solver.solve(input));",node:14 +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","const fs = require('fs'); + +// Functions for operations +function comboOperand(op, registers) { + const comboOperands = { 4: ""A"", 5: ""B"", 6: ""C"" }; + return op < 4 ? op : registers[comboOperands[op]]; +} + +function adv(op, registers) { + return Math.floor(registers[""A""] / Math.pow(2, comboOperand(op, registers))); +} + +function bxl(op, registers) { + return registers[""B""] ^ op; +} + +function bst(op, registers) { + return comboOperand(op, registers) % 8; +} + +function jnz(instPointer, op, registers) { + return registers[""A""] !== 0 ? op : instPointer + 2; +} + +function bxc(op, registers) { + return registers[""B""] ^ registers[""C""]; +} + +function out(op, registers) { + return (comboOperand(op, registers) % 8).toString(); +} + +function bdv(op, registers) { + return adv(op, registers); +} + +function cdv(op, registers) { + return adv(op, registers); +} + +// Read the input file +fs.readFile('input.txt', 'utf8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } + + const lines = data.split('\n'); + const registers = {}; + let program = []; + + // Parse the input data + lines.forEach(line => { + if (line.includes(""Register"")) { + const parts = line.trim().split("" ""); + registers[parts[1].slice(0, -1)] = parseInt(parts[2]); + } else if (line.includes(""Program"")) { + program = line.trim().slice(8).split("","").map(Number); + } + }); + + let instructionPointer = 0; + const output = []; + + // Execute the program + while (instructionPointer < program.length) { + const opcode = program[instructionPointer]; + const operand = program[instructionPointer + 1]; + + switch (opcode) { + case 0: + registers[""A""] = adv(operand, registers); + break; + case 1: + registers[""B""] = bxl(operand, registers); + break; + case 2: + registers[""B""] = bst(operand, registers); + break; + case 3: + instructionPointer = jnz(instructionPointer, operand, registers); + continue; + case 4: + registers[""B""] = bxc(operand, registers); + break; + case 5: + output.push(out(operand, registers)); + break; + case 6: + registers[""B""] = bdv(operand, registers); + break; + case 7: + registers[""C""] = cdv(operand, registers); + break; + default: + throw new Error(`Unknown opcode: ${opcode}`); + } + + instructionPointer += 2; + } + + console.log(""Program output:"", output.join("","")); +});",node:14 +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","const fs = require('fs'); + +// OpCodes +const ADV = 0; +const BXL = 1; +const BST = 2; +const JNZ = 3; +const BXC = 4; +const OUT = 5; +const BDV = 6; +const CDV = 7; + +// Function to handle operand conversion +function getComboOperand(operand, reg) { + if (operand >= 0 && operand <= 3) { + return operand; + } + + if (operand >= 4 && operand <= 6) { + return reg[String.fromCharCode(65 + operand - 4)]; + } + + throw new Error(`Unexpected operand ${operand}`); +} + +fs.readFile('input.txt', 'utf8', (err, data) => { + if (err) { + console.error('Error reading the file:', err); + return; + } + + const lines = data.split('\n'); + + // Register initialization + const reg = { + A: parseInt(lines[0].split("": "")[1]), + B: parseInt(lines[1].split("": "")[1]), + C: parseInt(lines[2].split("": "")[1]), + }; + + // Parsing the instructions + const instructions = lines[4].split("": "")[1].split("","").map(Number); + + let output = []; + let instrPtr = 0; + + // Execute instructions + while (instrPtr < instructions.length) { + let jump = false; + const [opcode, operand] = instructions.slice(instrPtr, instrPtr + 2); + + switch (opcode) { + case ADV: + reg['A'] = Math.floor(reg['A'] / Math.pow(2, getComboOperand(operand, reg))); + break; + + case BXL: + reg['B'] ^= operand; + break; + + case BST: + reg['B'] = getComboOperand(operand, reg) % 8; + break; + + case JNZ: + if (reg['A'] !== 0) { + instrPtr = operand; + jump = true; + } + break; + + case BXC: + reg['B'] ^= reg['C']; + break; + + case OUT: + output.push(getComboOperand(operand, reg) % 8); + break; + + case BDV: + reg['B'] = Math.floor(reg['A'] / Math.pow(2, getComboOperand(operand, reg))); + break; + + case CDV: + reg['C'] = Math.floor(reg['A'] / Math.pow(2, getComboOperand(operand, reg))); + break; + + default: + throw new Error(`Unexpected opcode ${opcode}`); + } + + if (!jump) { + instrPtr += 2; + } + } + + // Output the result + console.log(output.join("","")); +});",node:14 +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","const fs = require(""fs""); +const inputText = ""./input.txt""; + +fs.readFile(inputText, ""utf8"", (err, data) => { + if (err) { + console.error('Error reading file:', err); + return; + } + + const parsedData = {}; + data = data.split(""\n"").map(line => { + if (line.includes(""Register"")) { + line = line.replace(""Register "", """"); + } + line = line.split("": ""); + if (line[0] === ""Program"") { + line[1] = line[1].split("","").map(Number); + } else line[1] = parseInt(line[1]); + if (line[0]) parsedData[line[0]] = line[1]; + }) + + console.log(part1(parsedData)); +}); + +const part1 = (data) => { + let output = []; + let { A, B, C, Program: program } = data; + let instructionPointer = 0; + + const getCombo = operand => { + if (operand <= 3) return operand; + if (operand === 4) return A; + if (operand === 5) return B; + if (operand === 6) return C; + } + + const performInstruction = (opcode, operand) => { + switch (opcode) { + case 0: + A = Math.trunc(A / (2 ** getCombo(operand))); + break; + case 1: + B = B ^ operand; + break; + case 2: + B = getCombo(operand) % 8; + break; + case 3: + if (A !== 0) { + instructionPointer = operand; + return; + } + break; + case 4: + B = B ^ C; + break; + case 5: + output.push(getCombo(operand) % 8); + break; + case 6: + B = Math.trunc(A / (2 ** getCombo(operand))); + break; + case 7: + C = Math.trunc(A / (2 ** getCombo(operand))); + break; + } + instructionPointer += 2; + } + + while (instructionPointer < program.length) { + const opcode = program[instructionPointer]; + const operand = program[instructionPointer + 1]; + performInstruction(opcode, operand); + } + return output.join("",""); +}",node:14 +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","const fs = require('fs'); + +function runProgram(registers, program) { + let { A, B, C } = registers; + let ip = 0; + let output = []; + + while (ip < program.length) { + const opcode = program[ip]; + const operand = program[ip + 1]; + let operandValue; + + // Determine operand type + if (operand >= 0 && operand <= 3) { + operandValue = operand; + } else if (operand === 4) { + operandValue = A; + } else if (operand === 5) { + operandValue = B; + } else if (operand === 6) { + operandValue = C; + } else { + break; // Invalid operand + } + + switch (opcode) { + case 0: { // adv + const denominator = Math.pow(2, operandValue); + A = Math.trunc(A / denominator); + ip += 2; + break; + } + case 1: { // bxl + B ^= operand; + ip += 2; + break; + } + case 2: { // bst + B = operandValue % 8; + ip += 2; + break; + } + case 3: { // jnz + if (A !== 0) { + ip = operand; + } else { + ip += 2; + } + break; + } + case 4: { // bxc + B ^= C; + ip += 2; + break; + } + case 5: { // out + output.push(operandValue % 8); + ip += 2; + break; + } + case 6: { // bdv + const denominator6 = Math.pow(2, operandValue); + B = Math.trunc(A / denominator6); + ip += 2; + break; + } + case 7: { // cdv + const denominator7 = Math.pow(2, operandValue); + C = Math.trunc(A / denominator7); + ip += 2; + break; + } + default: + ip = program.length; // Halt on invalid opcode + } + } + + return output.join(','); +} + +// Read and parse input.txt +const inputPath = 'input.txt'; +const input = fs.readFileSync(inputPath, 'utf-8').trim().split('\n'); +let registers = { A: 0, B: 0, C: 0 }; +let program = []; + +input.forEach(line => { + if (line.startsWith('Register A:')) { + registers.A = parseInt(line.split(':')[1]); + } else if (line.startsWith('Register B:')) { + registers.B = parseInt(line.split(':')[1]); + } else if (line.startsWith('Register C:')) { + registers.C = parseInt(line.split(':')[1]); + } else if (line.startsWith('Program:')) { + program = line.split(':')[1].split(',').map(Number); + } +}); + +// Execute program and display output +const result = runProgram(registers, program); +console.log(result);",node:14 +2024,17,1,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string?","7,5,4,3,4,5,3,4,6","// solution for https://adventofcode.com/2024/day/17 part 1 + +""use strict"" + +const input = Deno.readTextFileSync(""day17-input.txt"").trim() + +var registerA = 0 +var registerB = 0 +var registerC = 0 + +const program = [ ] + +var pointer = 0 + +var output = [ ] + + +function main() { + + processInput() + + runProgram() + + console.log(""the answer is"", output.join("","")) +} + +function processInput() { + + const lines = input.split(""\n"") + + registerA = parseInt(lines.shift().trim().replace(""Register A: "", """")) + registerB = parseInt(lines.shift().trim().replace(""Register B: "", """")) + registerC = parseInt(lines.shift().trim().replace(""Register C: "", """")) + + lines.shift() // blank line + + const strProgram = lines.shift().trim().replace(""Program: "", """").split("","") + + for (const str of strProgram) { program.push(parseInt(str)) } +} + +/////////////////////////////////////////////////////////////////////////////// + +function runProgram() { + + while (true) { + + const opcode = program[pointer] + + if (opcode == undefined) { return } + + const operand = program[pointer + 1] + + if (opcode == 0) { adv(operand); pointer += 2; continue } + if (opcode == 1) { bxl(operand); pointer += 2; continue } + if (opcode == 2) { bst(operand); pointer += 2; continue } + if (opcode == 3) { jnz(operand); continue } + if (opcode == 4) { bxc(operand); pointer += 2; continue } + if (opcode == 5) { out(operand); pointer += 2; continue } + if (opcode == 6) { bdv(operand); pointer += 2; continue } + if (opcode == 7) { cdv(operand); pointer += 2; continue } + } +} + +function adv(operand) { registerA = Math.floor(registerA / Math.pow(2, combo(operand))) } + +function bdv(operand) { registerB = Math.floor(registerA / Math.pow(2, combo(operand))) } + +function cdv(operand) { registerC = Math.floor(registerA / Math.pow(2, combo(operand))) } + +function bst(operand) { registerB = combo(operand) % 8 } + +function bxl(operand) { registerB = registerB ^ operand } + +function bxc(operand) { registerB = registerB ^ registerC } + +function jnz(operand) { pointer = (registerA == 0) ? pointer + 2 : operand } + +function out(operand) { output.push(combo(operand) % 8) } + +function combo(operand) { + + if (operand < 4) { return operand } + + if (operand == 4) { return registerA } + if (operand == 5) { return registerB } + if (operand == 6) { return registerC } + + console.log(""error in function 'combo'"") +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 1ms",node:14 +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"const fs = require('fs'); + +let data = fs.readFileSync('input.txt', 'utf8'); + +let [regA, regB, regC] = [ + parseInt(/Register A: (\d+)/.exec(data)[1]), + parseInt(/Register B: (\d+)/.exec(data)[1]), + parseInt(/Register C: (\d+)/.exec(data)[1]) +]; + +let regIP = 0, regSkipInc = false; +let prog = /Program: (\d+(?:,\d+)*)/.exec(data)[1].split(','); +let stack = []; + +const cOp = { + '0': () => 0, + '1': () => 1, + '2': () => 2, + '3': () => 3, + '4': () => regA, + '5': () => regB, + '6': () => regC, + '7': () => null +}; + +const opcodes = { + '0': (op) => { regA = Math.floor(regA / (2 ** cOp[op]())); return regA; }, + '1': (op) => { regB ^= op; return regB; }, + '2': (op) => { regB = ((cOp[op]() % 8) + 8) % 8; return regB; }, + '3': (op) => { + if (regA !== 0) { + regIP = parseInt(op); + regSkipInc = true; + return true; + } + return false; + }, + '4': (op) => { regB ^= regC; return regB; }, + '5': (op) => { + let val = ((cOp[op]() % 8) + 8) % 8; + stack.push(val); + return val; + }, + '6': (op) => { regB = Math.floor(regA / (2 ** cOp[op]())); return regB; }, + '7': (op) => { regC = Math.floor(regA / (2 ** cOp[op]())); return regC; } +}; + +const main = () => { + while (regIP < prog.length) { + regSkipInc = false; + opcodes[prog[regIP]](prog[regIP + 1]); + if (!regSkipInc) regIP += 2; + } +}; + +main(); +console.log(prog.toString()); +console.log(""Part1"", stack.toString()); + +const main2 = () => { + let found = false; + let a = 0, s = 1; + while (!found) { + regA = a; + regIP = 0; + stack = []; + main(); + if (stack.toString() === prog.toString()) { + found = true; + regA = a; + } else if (stack.toString() === prog.slice(-s).toString()) { + a *= 8; + s++; + } else { + a++; + } + } + console.log(""Part2"", regA); +}; + +main2();",node:14 +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"import { readFileSync } from 'node:fs' +import { argv0 } from 'node:process'; + +let data = readFileSync('input.txt', { + encoding: 'utf8', + flag: 'r' +}); + +let regA = parseInt(/Register A: (\d+)/.exec(data)[1]); +let regB = parseInt(/Register B: (\d+)/.exec(data)[1]); +let regC = parseInt(/Register C: (\d+)/.exec(data)[1]); +let regIP = 0; // Instruction Pointer/Programme Counter +let regSkipInc = false; +let prog = /Program: (\d+(,\d+)*)/.exec(data)[1].split(','); +let stack = []; + +const cOp = { + '0': () => { return 0 }, + '1': () => { return 1 }, + '2': () => { return 2 }, + '3': () => { return 3 }, + '4': () => { return regA }, + '5': () => { return regB }, + '6': () => { return regC }, + '7': () => { return null } +} // Combo Operands + +const opcodes = { + '0' : (op) => { // adv + regA = Math.floor(regA / (Math.pow(2, cOp[op]()))); + return regA; + }, + '1': (op) => { // bxl + regB ^= op; + return regB; + }, + '2': (op) => { // bst + regB = ((cOp[op]() % 8) + 8) % 8; + return regB; + }, + '3': (op) => { // jnz + if (regA != 0) { + regIP = parseInt(op); + regSkipInc = true; + return true; + } else { + return false; + } + }, + '4': (op) => { // bxc + regB ^= regC; + return regB; + }, + '5': (op) => { // out + let val = ((cOp[op]() % 8) + 8) % 8; + stack.push(val); + return val; + }, + '6': (op) => { // bdv + regB = Math.floor(regA / (Math.pow(2, cOp[op]()))); + return regB; + }, + '7': (op) => { // cdv + regC = Math.floor(regA / (Math.pow(2, cOp[op]()))); + return regC; + } +} + +const main = () => { + while (regIP < prog.length) { + regSkipInc = false; + opcodes[prog[regIP]](prog[regIP+1]); + if (!regSkipInc) + regIP += 2; + } +} + +main(); +console.log(prog.toString()); +console.log(""Part1"",stack.toString()); + +const main2 = () => { + let found = false; + let a = 0; + let s = 1; + while (!found) { + regA = a; + regIP = 0; + stack = []; + main(); + if (stack.toString() === prog.toString()) { + found = true; + regA = a; + } else if (stack.toString() === prog.slice(-1 * s).toString()) { + a *= 8; + s++; + } else { + a++; + } + } + console.log(""part2"",regA); +} + +main2();",node:14 +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"const fs = require('fs'); + +let data = fs.readFileSync('input.txt', { + encoding: 'utf8', + flag: 'r' +}); + +let regA = parseInt(/Register A: (\d+)/.exec(data)[1]); +let regB = parseInt(/Register B: (\d+)/.exec(data)[1]); +let regC = parseInt(/Register C: (\d+)/.exec(data)[1]); +let regIP = 0; // Instruction Pointer/Program Counter +let regSkipInc = false; +let prog = /Program: (\d+(,\d+)*)/.exec(data)[1].split(','); +let stack = []; + +const cOp = { + '0': () => { return 0 }, + '1': () => { return 1 }, + '2': () => { return 2 }, + '3': () => { return 3 }, + '4': () => { return regA }, + '5': () => { return regB }, + '6': () => { return regC }, + '7': () => { return null } +}; // Combo Operands + +const opcodes = { + '0': (op) => { // adv + regA = Math.floor(regA / (Math.pow(2, cOp[op]()))); + return regA; + }, + '1': (op) => { // bxl + regB ^= op; + return regB; + }, + '2': (op) => { // bst + regB = ((cOp[op]() % 8) + 8) % 8; + return regB; + }, + '3': (op) => { // jnz + if (regA !== 0) { + regIP = parseInt(op); + regSkipInc = true; + return true; + } else { + return false; + } + }, + '4': (op) => { // bxc + regB ^= regC; + return regB; + }, + '5': (op) => { // out + let val = ((cOp[op]() % 8) + 8) % 8; + stack.push(val); + return val; + }, + '6': (op) => { // bdv + regB = Math.floor(regA / (Math.pow(2, cOp[op]()))); + return regB; + }, + '7': (op) => { // cdv + regC = Math.floor(regA / (Math.pow(2, cOp[op]()))); + return regC; + } +}; + +const main = () => { + while (regIP < prog.length) { + regSkipInc = false; + opcodes[prog[regIP]](prog[regIP + 1]); + if (!regSkipInc) + regIP += 2; + } +}; + +main(); +console.log(prog.toString()); +console.log(""Part1"", stack.toString()); + +const main2 = () => { + let found = false; + let a = 0; + let s = 1; + while (!found) { + regA = a; + regIP = 0; + stack = []; + main(); + if (stack.toString() === prog.toString()) { + found = true; + regA = a; + } else if (stack.toString() === prog.slice(-1 * s).toString()) { + a *= 8; + s++; + } else { + a++; + } + } + console.log(""Part2"", regA); +}; + +main2();",node:14 +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"const fs = require('fs'); + +const run = (fileContents) => { + let data = parseInput(fileContents); + let result1 = runProgram(structuredClone(data.registers), structuredClone(data.program)); + let result2 = part2(structuredClone(data.program)); + return { part1: result1.join(','), part2: result2 }; +} + +/** + * Part 2 solution + * @param {number[]} program The program to run + * @returns {number} The lowest correct initial value for A + */ +const part2 = (program) => { + let targetOutput = structuredClone(program).reverse().join(''); + let answers = []; + findInitialValue(0, program.length - 1, program, targetOutput, answers); + return Math.min(...answers); +} + +/** + * This recursively searches for a number to use for A. The program is always outputting + * (A/8^outputIndex)%8. This works in reverse solving for the last digit first by adding + * the previous partial sum to 8^outputIndexValue multiplied by x. X is a variable + * between 0 and 7. One of these values is guaranteed to give us the next value necessary since + * it covers all of the possible 3 bit values. If the output string matches we record + * the value since there could be multiple possible solutions for this. if not we check if + * it is partially matches for at least the values we have been working generate so far. + * If it does match then continue with this partial sum to the next power to see if a value can be made + * + * @param {number} sum Sum of the answer to this point + * @param {number} power The current power of 8 being checked for + * @param {number[]} program The program to run + * @param {string} target The reversed concatenated program + * @param {number[]} answers The answers that have been found so far + */ +const findInitialValue = (sum, power, program, target, answers) => { + for (let x = 0; x < 8; x++) { + let partialSum = sum + Math.pow(8, power) * x; + let registers = new Map(); + registers.set('A', partialSum); + registers.set('B', 0); + registers.set('C', 0); + + let output = runProgram(registers, program); + let revStrOutput = output.reverse().join(''); + + if (revStrOutput === target) { + answers.push(partialSum); + return; + } else { + let startOutput = revStrOutput.substring(0, target.length - power); + if (target.startsWith(startOutput)) { + findInitialValue(partialSum, power - 1, program, target, answers); + } + } + } +} + +/** + * The program computer as described in Part 1 + * @param {Map} registers The values to use for the program + * @param {number[]} program The program to run + * @returns {number[]} The output generated by the program + */ +const runProgram = (registers, program) => { + let output = []; + + const comboOperandValue = (operand) => { + if (operand >= 0 && operand <= 3) { + return operand; + } else if (operand === 4) { + return registers.get('A'); + } else if (operand === 5) { + return registers.get('B'); + } else if (operand === 6) { + return registers.get('C'); + } + throw new Error(""Invalid Combo Operand:"", operand); + } + + let current = 0; + while (current < program.length) { + let opCode = program[current]; + let operand = program[current + 1]; + let incrementCurrent = true; + + if (opCode === 0) { + let numerator = registers.get(""A""); + let operandVal = comboOperandValue(operand); + let denominator = Math.pow(2, operandVal); + registers.set('A', Math.floor(numerator / denominator)); + } else if (opCode === 1) { + let bVal = registers.get('B'); + registers.set('B', bVal ^ operand); + } else if (opCode === 2) { + let operandVal = comboOperandValue(operand); + registers.set('B', operandVal & 7); + } else if (opCode === 3) { + if (registers.get('A') !== 0) { + current = operand; + incrementCurrent = false; + } + } else if (opCode === 4) { + let bVal = registers.get('B'); + let cVal = registers.get('C'); + registers.set('B', bVal ^ cVal); + } else if (opCode === 5) { + let operandVal = comboOperandValue(operand); + output.push(operandVal & 7); + } else if (opCode === 6) { + let numerator = registers.get(""A""); + let operandVal = comboOperandValue(operand); + let denominator = Math.pow(2, operandVal); + registers.set('B', Math.floor(numerator / denominator)); + } else if (opCode === 7) { + let numerator = registers.get(""A""); + let operandVal = comboOperandValue(operand); + let denominator = Math.pow(2, operandVal); + registers.set('C', Math.floor(numerator / denominator)); + } else { + throw new Error(""Invalid OpCode:"", opCode); + } + + if (incrementCurrent) current += 2; + } + + return output; +} + +/** + * Parse the input into usable data + * @param {string[]} fileContents The lines of the input file as a string array + * @returns {registers: Map, number[]} The registers and program commands from the input file + */ +const parseInput = (fileContents) => { + let registerMode = true; + let registers = new Map(); + let program; + + for (let line of fileContents) { + if (line === '') { + registerMode = false; + continue; + } + if (registerMode) { + let matches = line.match(/Register ([ABC]): (\d+)/); + registers.set(matches[1], parseInt(matches[2])); + } else { + let matches = line.match(/Program: ([\d,]+)/); + program = matches[1].split(',').map(num => parseInt(num)); + } + } + + return { registers, program }; +} + +// Read the input.txt file and call the run function +fs.readFile('input.txt', 'utf-8', (err, data) => { + if (err) throw err; + console.log(run(data.split('\n'))); +});",node:14 +2024,17,2,"--- Day 17: Chronospatial Computer --- + +The Historians push the button on their strange device, but this time, you all just feel like you're falling. + +""Situation critical"", the device announces in a familiar voice. ""Bootstrapping process failed. Initializing debugger...."" + +The small handheld device suddenly unfolds into an entire computer! The Historians look around nervously before one of them tosses it to you. + +This seems to be a 3-bit computer: its program is a list of 3-bit numbers (0 through 7), like 0,1,2,3. The computer also has three registers named A, B, and C, but these registers aren't limited to 3 bits and can instead hold any integer. + +The computer knows eight instructions, each identified by a 3-bit number (called the instruction's opcode). Each instruction also reads the 3-bit number after it as an input; this is called its operand. + +A number called the instruction pointer identifies the position in the program from which the next opcode will be read; it starts at 0, pointing at the first 3-bit number in the program. Except for jump instructions, the instruction pointer increases by 2 after each instruction is processed (to move past the instruction's opcode and its operand). If the computer tries to read an opcode past the end of the program, it instead halts. + +So, the program 0,1,2,3 would run the instruction whose opcode is 0 and pass it the operand 1, then run the instruction having opcode 2 and pass it the operand 3, then halt. + +There are two types of operands; each instruction specifies the type of its operand. The value of a literal operand is the operand itself. For example, the value of the literal operand 7 is the number 7. The value of a combo operand can be found as follows: + +Combo operands 0 through 3 represent literal values 0 through 3. +Combo operand 4 represents the value of register A. +Combo operand 5 represents the value of register B. +Combo operand 6 represents the value of register C. +Combo operand 7 is reserved and will not appear in valid programs. +The eight instructions are as follows: + +The adv instruction (opcode 0) performs division. The numerator is the value in the A register. The denominator is found by raising 2 to the power of the instruction's combo operand. (So, an operand of 2 would divide A by 4 (2^2); an operand of 5 would divide A by 2^B.) The result of the division operation is truncated to an integer and then written to the A register. + +The bxl instruction (opcode 1) calculates the bitwise XOR of register B and the instruction's literal operand, then stores the result in register B. + +The bst instruction (opcode 2) calculates the value of its combo operand modulo 8 (thereby keeping only its lowest 3 bits), then writes that value to the B register. + +The jnz instruction (opcode 3) does nothing if the A register is 0. However, if the A register is not zero, it jumps by setting the instruction pointer to the value of its literal operand; if this instruction jumps, the instruction pointer is not increased by 2 after this instruction. + +The bxc instruction (opcode 4) calculates the bitwise XOR of register B and register C, then stores the result in register B. (For legacy reasons, this instruction reads an operand but ignores it.) + +The out instruction (opcode 5) calculates the value of its combo operand modulo 8, then outputs that value. (If a program outputs multiple values, they are separated by commas.) + +The bdv instruction (opcode 6) works exactly like the adv instruction except that the result is stored in the B register. (The numerator is still read from the A register.) + +The cdv instruction (opcode 7) works exactly like the adv instruction except that the result is stored in the C register. (The numerator is still read from the A register.) + +Here are some examples of instruction operation: + +If register C contains 9, the program 2,6 would set register B to 1. +If register A contains 10, the program 5,0,5,1,5,4 would output 0,1,2. +If register A contains 2024, the program 0,1,5,4,3,0 would output 4,2,5,6,7,7,7,7,3,1,0 and leave 0 in register A. +If register B contains 29, the program 1,7 would set register B to 26. +If register B contains 2024 and register C contains 43690, the program 4,0 would set register B to 44354. +The Historians' strange device has finished initializing its debugger and is displaying some information about the program it is trying to run (your puzzle input). For example: + +Register A: 729 +Register B: 0 +Register C: 0 + +Program: 0,1,5,4,3,0 +Your first task is to determine what the program is trying to output. To do this, initialize the registers to the given values, then run the given program, collecting any output produced by out instructions. (Always join the values produced by out instructions with commas.) After the above program halts, its final output will be 4,6,3,5,6,3,5,2,1,0. + +Using the information provided by the debugger, initialize the registers to the given values, then run the program. Once it halts, what do you get if you use commas to join the values it output into a single string? + +Your puzzle answer was 7,5,4,3,4,5,3,4,6. + +--- Part Two --- + +Digging deeper in the device's manual, you discover the problem: this program is supposed to output another copy of the program! Unfortunately, the value in register A seems to have been corrupted. You'll need to find a new value to which you can initialize register A so that the program's output instructions produce an exact copy of the program itself. + +For example: + +Register A: 2024 +Register B: 0 +Register C: 0 + +Program: 0,3,5,4,3,0 +This program outputs a copy of itself if register A is instead initialized to 117440. (The original initial value of register A, 2024, is ignored.) + +What is the lowest positive initial value for register A that causes the program to output a copy of itself?",164278899142333,"// solution for https://adventofcode.com/2024/day/17 part 2 + +// analysing *MY* puzzle entry I came to some conclusions: +// +// - register A is the main register that holds data and commands the execution +// - register B and register C only exist for helping temporarily +// - near the end of the program there is the *only* output instruction (outputs some_value % 8) +// - there is *only* one jump instruction, it is in the last position, if register A is +// zero it finishes the execution, otherwise it jumps back to the first line of the program +// +// - register A % 8 (its *THREE BITS* TO THE RIGHT) controls the value of each output +// - register A / pow(8, n) (its *OTHER BITS*) controls how many loops (outputs) will exist + +""use strict"" + +const input = Deno.readTextFileSync(""day17-input.txt"").trim() + +var originalA = 0 // unused +var originalB = 0 +var originalC = 0 + +const program = [ ] + + +function main() { + + processInput() + + const register = search(BigInt(0), 1) + + console.log(""the answer is"", parseInt(register)) +} + +function processInput() { + + const lines = input.split(""\n"") + + originalA = BigInt(lines.shift().trim().replace(""Register A: "", """")) + originalB = BigInt(lines.shift().trim().replace(""Register B: "", """")) + originalC = BigInt(lines.shift().trim().replace(""Register C: "", """")) + + lines.shift() // blank line + + const tokens = lines.shift().trim().replace(""Program: "", """").split("","") + + for (const token of tokens) { program.push(parseInt(token)) } +} + +/////////////////////////////////////////////////////////////////////////////// + +function search(register, tail) { // wants to match the tail // 'tail' means the length of the tail + + for (let delta = 0; delta < 8; delta++) { + + const newRegister = register * BigInt(8) + BigInt(delta) + + const output = runProgram(newRegister) + + if (program.at(-tail) != output.at(-tail)) { continue } // tails don't match + + if (program.length == output.length) { return newRegister } // solved! + + const ultimateRegister = search(newRegister, tail + 1) + + if (ultimateRegister != 0) { return ultimateRegister } + } + + return 0 +} + +/////////////////////////////////////////////////////////////////////////////// + +function runProgram(register) { + + let registerA = register + let registerB = originalB + let registerC = originalC + + let pointer = 0 + + const output = [ ] + + while (true) { + + const opcode = program[pointer] + + if (opcode == undefined) { return output } + + const operand = BigInt(program[pointer + 1]) + + if (opcode == 0) { adv(operand); pointer += 2; continue } + if (opcode == 1) { bxl(operand); pointer += 2; continue } + if (opcode == 2) { bst(operand); pointer += 2; continue } + if (opcode == 3) { jnz(operand); continue } + if (opcode == 4) { bxc(operand); pointer += 2; continue } + if (opcode == 5) { out(operand); pointer += 2; continue } + if (opcode == 6) { bdv(operand); pointer += 2; continue } + if (opcode == 7) { cdv(operand); pointer += 2; continue } + } + + + function adv(operand) { registerA = registerA / pow(BigInt(2), combo(operand)) } // BigInt dismisses Math.floor + + function bdv(operand) { registerB = registerA / pow(BigInt(2), combo(operand)) } // BigInt dismisses Math.floor + + function cdv(operand) { registerC = registerA / pow(BigInt(2), combo(operand)) } // BigInt dismisses Math.floor + + function bst(operand) { registerB = combo(operand) % BigInt(8) } + + function bxl(operand) { registerB = registerB ^ operand } + + function bxc(operand) { registerB = registerB ^ registerC } + + function jnz(operand) { pointer = (registerA == 0) ? pointer + 2 : parseInt(operand) } + + function out(operand) { output.push(combo(operand) % BigInt(8)) } + + function combo(operand) { + + if (operand < 4) { return operand } + if (operand == 4) { return registerA } + if (operand == 5) { return registerB } + if (operand == 6) { return registerC } + + console.log(""error in function 'combo'"") + } + + function pow(base, expoent) { // necessary because Math.pow doesn't accept BigInt + + let result = BigInt(1) + + for (let n = BigInt(0); n < expoent; n++) { result *= base } + + return result + } +} + +/////////////////////////////////////////////////////////////////////////////// + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 7ms",node:14 +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"const fs = require('fs'); + +// Read the first 1024 coordinates from input.txt +const data = fs.readFileSync('input.txt', 'utf8'); +const lines = data.trim().split('\n').slice(0, 1024); + +// Initialize a 71x71 grid +const gridSize = 71; +const grid = Array.from({ length: gridSize }, () => Array(gridSize).fill(0)); + +// Mark the corrupted cells +for (const line of lines) { + const [xStr, yStr] = line.split(','); + const x = parseInt(xStr, 10); + const y = parseInt(yStr, 10); + if (x >= 0 && x < gridSize && y >= 0 && y < gridSize) { + grid[y][x] = 1; // Mark as corrupted + } +} + +// BFS to find the shortest path +function bfs(startX, startY, endX, endY) { + const visited = Array.from({ length: gridSize }, () => Array(gridSize).fill(false)); + const queue = [{ x: startX, y: startY, steps: 0 }]; + visited[startY][startX] = true; + + const directions = [ + { dx: 0, dy: -1 }, // up + { dx: 0, dy: 1 }, // down + { dx: -1, dy: 0 }, // left + { dx: 1, dy: 0 }, // right + ]; + + while (queue.length > 0) { + const { x, y, steps } = queue.shift(); + + if (x === endX && y === endY) { + console.log(steps); + return; + } + + for (const { dx, dy } of directions) { + const nx = x + dx; + const ny = y + dy; + + if ( + nx >= 0 && nx < gridSize && + ny >= 0 && ny < gridSize && + !visited[ny][nx] && + grid[ny][nx] === 0 + ) { + visited[ny][nx] = true; + queue.push({ x: nx, y: ny, steps: steps + 1 }); + } + } + } + + console.log('No path found'); +} + +bfs(0, 0, 70, 70);",node:14 +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"const fs = require('fs'); + +// Parses the input file and returns a list of tuples containing integer pairs. +function parseInput(filePath) { + const file = fs.readFileSync(filePath, 'utf-8').split('\n'); + return file.map(line => line.trim().split(',').map(Number)); +} + +// Initializes a square grid of the given size with all cells set to '.' +function initializeGrid(size) { + return Array.from({ length: size }, () => Array(size).fill('.')); +} + +// Simulates the falling of bytes in a grid +function simulateFallingBytes(grid, bytePositions, numBytes) { + for (let i = 0; i < numBytes; i++) { + const [x, y] = bytePositions[i]; + grid[y][x] = '#'; + } +} + +// Finds the shortest path in a grid from the top-left corner to the bottom-right corner +function findShortestPath(grid) { + const size = grid.length; + const directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]; + const queue = [[0, 0, 0]]; // [x, y, steps] + const visited = new Set(); + visited.add('0,0'); + + while (queue.length > 0) { + const [x, y, steps] = queue.shift(); + + if (x === size - 1 && y === size - 1) { + return steps; + } + + for (const [dx, dy] of directions) { + const nx = x + dx; + const ny = y + dy; + if (nx >= 0 && nx < size && ny >= 0 && ny < size && grid[ny][nx] === '.' && !visited.has(`${nx},${ny}`)) { + visited.add(`${nx},${ny}`); + queue.push([nx, ny, steps + 1]); + } + } + } + + return -1; // No path found +} + +// Main function +const filePath = 'input.txt'; +const bytePositions = parseInput(filePath); +const gridSize = 71; // For the actual problem, use 71; for the example, use 7 +const grid = initializeGrid(gridSize); +simulateFallingBytes(grid, bytePositions, 1024); +const steps = findShortestPath(grid); +console.log(`Minimum number of steps needed to reach the exit: ${steps}`);",node:14 +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"// solution for https://adventofcode.com/2024/day/18 part 1 + +""use strict"" + +const input = Deno.readTextFileSync(""day18-input.txt"").trim() + +const width = 71 +const height = 71 + +const map = [ ] + +const BIG = 1000 * 1000 // means cell not walked + + +function main() { + + makeMap() + + processInput() + + walk() + + // showMap() + + console.log(""the answer is"", map[width - 1][height - 1].distance) +} + +function makeMap() { + + for (let row = 0; row < height; row++) { + + const line = [ ] + map.push(line) + + for (let col = 0; col < width; col++) { line.push(createCell(row, col)) } + } +} + +function createCell(row, col) { + + return { ""row"": row, ""col"": col, ""blocked"": false, ""distance"": BIG } +} + +function processInput() { + + const lines = input.split(""\n"") + + for (let n = 0; n < 1024; n++) { + + const coords = lines.shift().trim().split("","") + + const row = parseInt(coords.shift()) + const col = parseInt(coords.shift()) + + map[row][col].blocked = true + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function walk() { + + const homeCell = map[0][0] + + homeCell.distance = 0 + + let cellsToWalk = [ homeCell ] + + while (true) { + + const newCellsToWalk = [ ] + + for (const cell of cellsToWalk) { + + const row = cell.row + const col = cell.col + const distance = cell.distance + 1 + + grabCell(row - 1, col, distance, newCellsToWalk) + grabCell(row + 1, col, distance, newCellsToWalk) + grabCell(row, col - 1, distance, newCellsToWalk) + grabCell(row, col + 1, distance, newCellsToWalk) + } + + cellsToWalk = newCellsToWalk + + if (cellsToWalk.length == 0) { return } + } +} + +function grabCell(row, col, distance, newCellsToWalk) { + + if (row < 0) { return } + if (col < 0) { return } + + if (row == height) { return } + if (col == width) { return } + + const cell = map[row][col] + + if (cell.blocked) { return } + + if (cell.distance <= distance) { return } + + cell.distance = distance + + newCellsToWalk.push(cell) +} + +/////////////////////////////////////////////////////////////////////////////// + +function showMap() { + + for (const line of map) { + + let s = """" + for (const cell of line) { + + let c = ""."" + if (cell.blocked) { c = ""#"" } + if (cell.distance != BIG) { c = ""O"" } + s += c + } + console.log(s) + } +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 5ms",node:14 +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"const fs = require('fs'); + +const input_text = fs.readFileSync('input.txt', 'utf-8').split('\n'); + +const grid_size = 70; +const num_fallen = 1024; +const bytes = new Set(); + +for (let i = 0; i < num_fallen; i++) { + const [byte_x, byte_y] = input_text[i].split("",""); + bytes.add([parseInt(byte_x), parseInt(byte_y)].toString()); +} + +const movements = [[-1, 0], [1, 0], [0, 1], [0, -1]]; +const explored = new Set(); +const discovered = [[0, 0, 0]]; + +while (discovered.length > 0) { + discovered.sort((a, b) => a[0] - b[0]); + const [distance, byte_x, byte_y] = discovered.shift(); + + if (!explored.has([byte_x, byte_y].toString())) { + explored.add([byte_x, byte_y].toString()); + + if (byte_x === byte_y && byte_x === grid_size) { + console.log(distance); + break; + } + + for (const movement of movements) { + const new_position = [byte_x + movement[0], byte_y + movement[1]]; + const new_position_str = new_position.toString(); + + if ( + !bytes.has(new_position_str) && + !explored.has(new_position_str) && + new_position.every(coord => coord >= 0 && coord <= grid_size) + ) { + discovered.push([distance + 1, ...new_position]); + } + } + } +}",node:14 +2024,18,1,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit?",506,"const fs = require('fs'); + +// Read the input file and parse the coordinates +const lines = fs.readFileSync('input.txt', 'utf8').trim().split(""\n""); +const coords = new Set(lines.slice(0, 1024).map(line => { + const [x, y] = line.split("",""); + return `${x},${y}`; +})); + +const dd = [[1, 0], [0, 1], [-1, 0], [0, -1]]; +const N = 70; + +// Heuristic for A* +function h(i, j) { + return Math.abs(N - i) + Math.abs(N - j); +} + +function inGrid(i, j) { + return i >= 0 && i <= N && j >= 0 && j <= N && !coords.has(`${i},${j}`); +} + +const q = [[h(0, 0), 0, 0]]; // [cost, i, j] +const cost = {}; + +while (q.length > 0) { + // Sort by cost (A* logic) + q.sort((a, b) => a[0] - b[0]); + const [c, i, j] = q.shift(); + + if (cost[`${i},${j}`] !== undefined) { + continue; + } + + cost[`${i},${j}`] = c - h(i, j); + + if (i === N && j === N) { + console.log(cost[`${i},${j}`]); + break; + } + + for (const [di, dj] of dd) { + const ii = i + di; + const jj = j + dj; + if (inGrid(ii, jj)) { + q.push([cost[`${i},${j}`] + 1 + h(ii, jj), ii, jj]); + } + } +}",node:14 +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","const fs = require('fs'); +const {log} = require('console'); + +const bytes = fs.readFileSync('input.txt', 'utf-8').split('\n').map(line => line.split(',').map(x => parseInt(x))); + +const cols = 70; +const rows = 70; +let walls = bytes.slice(0, 1024); +const start = { + row: 0, + col: 0, + g: 0, + h: 140, + f: 0 +}; +const end = { + row: 70, + col: 70, + g: 0, + h: 0, + f: 0 +}; + +// A* pathfinding algorithm +function astar(start, end) { + const openSet = []; + const closedSet = []; + openSet.push(start); + + while (openSet.length > 0) { + // Find the node with the lowest total cost in the open set + let currentNode = openSet[0]; + for (let i = 1; i < openSet.length; i++) { + if (openSet[i].f < currentNode.f || (openSet[i].f === currentNode.f && openSet[i].h < currentNode.h)) { + currentNode = openSet[i]; + } + } + + // Remove the current node from the open set + openSet.splice(openSet.indexOf(currentNode), 1); + closedSet.push(currentNode); + + // If the current node is the goal, reconstruct the path + if (currentNode.row === end.row && currentNode.col === end.col) { + let path = []; + let temp = currentNode; + while (temp) { + path.push(temp); + temp = temp.parent; + } + return path.reverse(); + } + + // Generate neighbors of the current node + const neighbors = []; + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; // Right, Down, Left, Up + + for (let dir of directions) { + const neighborRow = currentNode.row + dir[0]; + const neighborCol = currentNode.col + dir[1]; + + if (isValidCell(neighborRow, neighborCol)) { + const neighbor = { + row: neighborRow, + col: neighborCol, + g: currentNode.g + 1, // Cost to move to a neighboring cell is 1 + h: heuristic({row: neighborRow, col: neighborCol}, end), + f: 0, + parent: currentNode, + }; + + neighbor.f = neighbor.g + neighbor.h; + + // Check if the neighbor is already in the closed set + if (closedSet.some((node) => node.row === neighbor.row && node.col === neighbor.col)) { + continue; + } + + // Check if the neighbor is already in the open set + const openSetNode = openSet.find((node) => node.row === neighbor.row && node.col === neighbor.col); + if (!openSetNode || neighbor.g < openSetNode.g) { + openSet.push(neighbor); + } + } + } + } +} + +// Helper function to calculate the heuristic (Manhattan distance) +function heuristic(a, b) { + return Math.abs(a.row - b.row) + Math.abs(a.col - b.col); +} + +// Helper function to check if a cell is valid and not an obstacle +function isValidCell(row, col) { + if (row < 0 || row > rows || col < 0 || col > cols) { + return false; + } + return !walls.some(([r, c]) => r === row && c === col); +} + + +// console.log(bytes); +// console.log(walls); +let path = astar(start, end); +console.log('part 1', path.length - 1); +// for (let p of path) { +// console.log(p.row,p.col) +// } + +let wallsEnd = 1025; +while (true) { + console.log(wallsEnd); + walls = bytes.slice(0, wallsEnd); + if (!astar(start, end)) { + break; + } + wallsEnd++; +} + +console.log('part 2', bytes[wallsEnd - 1]);",node:14 +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","const fs = require('fs'); + +const l = fs.readFileSync('input.txt', 'utf-8').split('\n').map(line => line.split(',').map(Number)); + +const max_x = Math.max(...l.map(coord => coord[0])); +const max_y = Math.max(...l.map(coord => coord[1])); + +function P2() { + for (let find = 1024; find < l.length; find++) { + const grid = Array.from({ length: max_x + 1 }, () => Array(max_y + 1).fill(""."")); + + for (let i = 0; i < find; i++) { + const [x, y] = l[i]; + grid[x][y] = ""#""; + } + + function bfs(grid, start, end) { + const rows = grid.length; + const cols = grid[0].length; + const directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]; + const queue = [[start, 0]]; + const visited = new Set(); + + while (queue.length > 0) { + const [[x, y], dist] = queue.shift(); + + if (x === end[0] && y === end[1]) { + return dist; + } + + if (visited.has(`${x},${y}`) || grid[x][y] === ""#"") { + continue; + } + + visited.add(`${x},${y}`); + + for (const [dx, dy] of directions) { + const nx = x + dx; + const ny = y + dy; + if (nx >= 0 && nx < rows && ny >= 0 && ny < cols && !visited.has(`${nx},${ny}`)) { + queue.push([[nx, ny], dist + 1]); + } + } + } + + return -1; + } + + if (bfs(grid, [0, 0], [max_x, max_y]) === -1) { + return l[find - 1]; + } + } +} + +console.log(P2());",node:14 +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","const fs = require('fs'); + +// Read all coordinates from input.txt +const data = fs.readFileSync('input.txt', 'utf8'); +const lines = data.trim().split('\n'); + +const gridSize = 71; +const grid = Array.from({ length: gridSize }, () => Array(gridSize).fill(0)); + +function bfs(startX, startY, endX, endY) { + const visited = Array.from({ length: gridSize }, () => Array(gridSize).fill(false)); + const queue = [{ x: startX, y: startY }]; + visited[startY][startX] = true; + + const directions = [ + { dx: 0, dy: -1 }, // up + { dx: 0, dy: 1 }, // down + { dx: -1, dy: 0 }, // left + { dx: 1, dy: 0 }, // right + ]; + + while (queue.length > 0) { + const { x, y } = queue.shift(); + + if (x === endX && y === endY) { + return true; // Path exists + } + + for (const { dx, dy } of directions) { + const nx = x + dx; + const ny = y + dy; + + if ( + nx >= 0 && nx < gridSize && + ny >= 0 && ny < gridSize && + !visited[ny][nx] && + grid[ny][nx] === 0 + ) { + visited[ny][nx] = true; + queue.push({ x: nx, y: ny }); + } + } + } + + return false; // No path found +} + +for (let i = 0; i < lines.length; i++) { + const [xStr, yStr] = lines[i].split(','); + const x = parseInt(xStr, 10); + const y = parseInt(yStr, 10); + + if (x >= 0 && x < gridSize && y >= 0 && y < gridSize) { + grid[y][x] = 1; // Mark as corrupted + } + + // Check if path is still available + if (!bfs(0, 0, gridSize - 1, gridSize - 1)) { + console.log(`${x},${y}`); + break; + } +}",node:14 +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","// solution for https://adventofcode.com/2024/day/18 part 2 + +// expecting NO duplicated coordinates! + +""use strict"" + +const input = Deno.readTextFileSync(""day18-input.txt"").trim() + +const width = 71 +const height = 71 + +const map = [ ] + +const strCoordinates = [ ] + + +function main() { + + makeMap() + + processInput() + + console.log(""the answer is"", findTheFirstBlockingByte()) +} + +function makeMap() { + + for (let row = 0; row < height; row++) { + + const line = [ ] + map.push(line) + + for (let col = 0; col < width; col++) { line.push(createCell(row, col)) } + } +} + +function createCell(row, col) { + + return { ""row"": row, ""col"": col, ""blockRound"": 1000 * 1000, ""walkRound"": -1 } +} + +function processInput() { + + const lines = input.split(""\n"") + + while (lines.length != 0) { + + const str = lines.shift().trim() + + strCoordinates.push(str) + + const coords = str.split("","") + + const row = parseInt(coords.shift()) + const col = parseInt(coords.shift()) + + map[row][col].blockRound = strCoordinates.length - 1 + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function walk(walkRound) { + + const goalRow = width - 1 + const goalCol = height - 1 + + const homeCell = map[0][0] + + homeCell.walkRound = walkRound + + let cellsToWalk = [ homeCell ] + + while (true) { + + const newCellsToWalk = [ ] + + for (const cell of cellsToWalk) { + + const row = cell.row + const col = cell.col + + if (row == goalRow && col == goalCol) { return true } + + grabCell(row - 1, col, walkRound, newCellsToWalk) + grabCell(row + 1, col, walkRound, newCellsToWalk) + grabCell(row, col - 1, walkRound, newCellsToWalk) + grabCell(row, col + 1, walkRound, newCellsToWalk) + } + + cellsToWalk = newCellsToWalk + + if (cellsToWalk.length == 0) { return false } + } +} + +function grabCell(row, col, walkRound, newCellsToWalk) { + + if (row < 0) { return } + if (col < 0) { return } + + if (row == height) { return } + if (col == width) { return } + + const cell = map[row][col] + + if (cell.blockRound <= walkRound) { return } + + if (cell.walkRound == walkRound) { return } + + cell.walkRound = walkRound + + newCellsToWalk.push(cell) +} + +/////////////////////////////////////////////////////////////////////////// + +function findTheFirstBlockingByte() { + + let highestFree = 0 + let lowestBlocked = strCoordinates.length - 1 + + while (true) { + + if (highestFree + 1 == lowestBlocked) { return strCoordinates[lowestBlocked] } + + let round = Math.floor((highestFree + lowestBlocked) / 2) + + const free = walk(round) + + if (free) { highestFree = round } else { lowestBlocked = round } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function showMap(walkRound) { + + for (const line of map) { + + let s = """" + for (const cell of line) { + + let c = ""."" + if (cell.blockRound <= walkRound) { c = ""#"" } + if (cell.walkRound == walkRound) { c = ""O"" } + s += c + } + console.log(s) + } +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 8ms",node:14 +2024,18,2,"--- Day 18: RAM Run --- + +You and The Historians look a lot more pixelated than you remember. You're inside a computer at the North Pole! + +Just as you're about to check out your surroundings, a program runs up to you. ""This region of memory isn't safe! The User misunderstood what a pushdown automaton is and their algorithm is pushing whole bytes down on top of us! Run!"" + +The algorithm is fast - it's going to cause a byte to fall into your memory space once every nanosecond! Fortunately, you're faster, and by quickly scanning the algorithm, you create a list of which bytes will fall (your puzzle input) in the order they'll land in your memory space. + +Your memory space is a two-dimensional grid with coordinates that range from 0 to 70 both horizontally and vertically. However, for the sake of example, suppose you're on a smaller grid with coordinates that range from 0 to 6 and the following list of incoming byte positions: + +5,4 +4,2 +4,5 +3,0 +2,1 +6,3 +2,4 +1,5 +0,6 +3,3 +2,6 +5,1 +1,2 +5,5 +2,5 +6,5 +1,4 +0,4 +6,4 +1,1 +6,1 +1,0 +0,5 +1,6 +2,0 +Each byte position is given as an X,Y coordinate, where X is the distance from the left edge of your memory space and Y is the distance from the top edge of your memory space. + +You and The Historians are currently in the top left corner of the memory space (at 0,0) and need to reach the exit in the bottom right corner (at 70,70 in your memory space, but at 6,6 in this example). You'll need to simulate the falling bytes to plan out where it will be safe to run; for now, simulate just the first few bytes falling into your memory space. + +As bytes fall into your memory space, they make that coordinate corrupted. Corrupted memory coordinates cannot be entered by you or The Historians, so you'll need to plan your route carefully. You also cannot leave the boundaries of the memory space; your only hope is to reach the exit. + +In the above example, if you were to draw the memory space after the first 12 bytes have fallen (using . for safe and # for corrupted), it would look like this: + +...#... +..#..#. +....#.. +...#..# +..#..#. +.#..#.. +#.#.... +You can take steps up, down, left, or right. After just 12 bytes have corrupted locations in your memory space, the shortest path from the top left corner to the exit would take 22 steps. Here (marked with O) is one such path: + +OO.#OOO +.O#OO#O +.OOO#OO +...#OO# +..#OO#. +.#.O#.. +#.#OOOO +Simulate the first kilobyte (1024 bytes) falling onto your memory space. Afterward, what is the minimum number of steps needed to reach the exit? + +Your puzzle answer was 506. + +--- Part Two --- + +The Historians aren't as used to moving around in this pixelated universe as you are. You're afraid they're not going to be fast enough to make it to the exit before the path is completely blocked. + +To determine how fast everyone needs to go, you need to determine the first byte that will cut off the path to the exit. + +In the above example, after the byte at 1,1 falls, there is still a path to the exit: + +O..#OOO +O##OO#O +O#OO#OO +OOO#OO# +###OO## +.##O### +#.#OOOO +However, after adding the very next byte (at 6,1), there is no longer a path to the exit: + +...#... +.##..## +.#..#.. +...#..# +###..## +.##.### +#.#.... +So, in this example, the coordinates of the first byte that prevents the exit from being reachable are 6,1. + +Simulate more of the bytes that are about to corrupt your memory space. What are the coordinates of the first byte that will prevent the exit from being reachable from your starting position? (Provide the answer as two integers separated by a comma with no other characters.)","62,6","const fs = require('fs'); + +const input_text = fs.readFileSync('input.txt', 'utf-8').split('\n'); + +const grid_size = 70; +const bytes_list = input_text.map(byte => { + const [byte_x, byte_y] = byte.split("",""); + return [parseInt(byte_x), parseInt(byte_y)]; +}); + +const movements = [[-1, 0], [1, 0], [0, 1], [0, -1]]; + +let bytes_needed_lower = 0; +let bytes_needed_upper = bytes_list.length - 1; + +while (bytes_needed_lower < bytes_needed_upper) { + const mid = Math.floor((bytes_needed_lower + bytes_needed_upper) / 2); + const bytes = new Set(bytes_list.slice(0, mid).map(byte => byte.toString())); + const explored = new Set(); + const discovered = [[0, 0, 0]]; + + while (discovered.length > 0) { + discovered.sort((a, b) => a[0] - b[0]); + const [distance, byte_x, byte_y] = discovered.shift(); + + if (!explored.has([byte_x, byte_y].toString())) { + explored.add([byte_x, byte_y].toString()); + + if (byte_x === byte_y && byte_x === grid_size) { + break; + } + + for (const movement of movements) { + const new_position = [byte_x + movement[0], byte_y + movement[1]]; + const new_position_str = new_position.toString(); + + if ( + !bytes.has(new_position_str) && + !explored.has(new_position_str) && + new_position.every(coord => coord >= 0 && coord <= grid_size) + ) { + discovered.push([distance + 1, ...new_position]); + } + } + } + } + + if (discovered.length === 0) { + bytes_needed_upper = mid; + } else { + bytes_needed_lower = mid + 1; + } +} + +console.log(bytes_list[bytes_needed_lower - 1].join(','));",node:14 +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"// solution for https://adventofcode.com/2024/day/19 part 1 + +""use strict"" + +const input = Deno.readTextFileSync(""day19-input.txt"").trim() + +const allTargets = [ ] + +const patternsBySize = { } // { size: list } + +const patternsByLetter = { } // { letter: list } + +const cache = { } // token: true/false + + +function main() { + + processInput() + + simplifyPatterns() + + fillPatternsByLetter() + + let count = 0 + + for (const target of allTargets) { + + if (isComposable(target)) { count += 1 } + } + + console.log(""the answer is"", count) +} + +function processInput() { + + const sections = input.split(""\n\n"") + + const rawTargets = sections.pop().trim().split(""\n"") + + for (const rawTarget of rawTargets) { allTargets.push(rawTarget.trim()) } + + const patterns = sections.pop().trim().split("", "") + + for (const pattern of patterns) { + + const size = pattern.length + + if (patternsBySize[size] == undefined) { patternsBySize[size] = [ ] } + + patternsBySize[size].push(pattern) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function simplifyPatterns() { + + const maxSize = Object.keys(patternsBySize).length + + for (let size = 2; size <= maxSize; size++) { simplifyPatternsThisSize(size) } +} + +function simplifyPatternsThisSize(size) { + + const newList = [ ] + + for (const pattern of patternsBySize[size]) { + + if (! isRedundant(pattern, 1)) { newList.push(pattern) } + } + + patternsBySize[size] = newList +} + +function isRedundant(sourcePattern, reductor) { + + const maxSize = sourcePattern.length - reductor + + for (let size = maxSize; size > 0; size--) { // decreasing + + for (const pattern of patternsBySize[size]) { + + if (! sourcePattern.startsWith(pattern)) { continue } + + const remain = sourcePattern.replace(pattern, """") + + if (remain == """") { return true } + + if (isRedundant(remain, 0)) { return true } + } + } + + return false +} + +/////////////////////////////////////////////////////////////////////////////// + +function fillPatternsByLetter() { + + const maxSize = Object.keys(patternsBySize).length + + for (let size = maxSize; size > 0; size--) { // decreasing + + for (const pattern of patternsBySize[size]) { + + const letter = pattern[0] + + if (patternsByLetter[letter] == undefined) { patternsByLetter[letter] = [ ] } + + patternsByLetter[letter].push(pattern) + } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function isComposable(target) { + + if (cache[target] !== undefined) { return cache[target] } + + for (const pattern of patternsByLetter[target[0]]) { + + if (! target.startsWith(pattern)) { continue } + + const remain = target.replace(pattern, """") + + if (remain == """") { cache[target] = true; return true } + + if (isComposable(remain)) { cache[target] = true; return true } + } + + cache[target] = false + return false +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 18ms",node:14 +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"const fs = require('fs'); + +function isPatternPossible(pattern, towels, visited) { + if (pattern === """") { + return true; + } + + visited.add(pattern); + + return towels.some(towel => + pattern.startsWith(towel) && + !visited.has(pattern.slice(towel.length)) && + isPatternPossible(pattern.slice(towel.length), towels, visited) + ); +} + +fs.readFile('input.txt', 'utf8', (err, data) => { + if (err) throw err; + + const lines = data.split('\n'); + const towels = lines[0].split("","").map(s => s.trim()); + const patterns = lines.slice(2); + + const validPatternCount = patterns.reduce((count, pattern) => { + return count + (isPatternPossible(pattern, towels, new Set()) ? 1 : 0); + }, 0); + + console.log(validPatternCount); +});",node:14 +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"const fs = require('fs'); + +fs.readFile('./day_19.in', 'utf8', (err, data) => { + if (err) throw err; + + const lines = data.split('\n'); + const units = lines[0].split(', ').map(s => s.trim()); + const designs = lines.slice(2); + + function possible(design) { + const n = design.length; + const dp = new Array(n).fill(false); + for (let i = 0; i < n; i++) { + if (units.includes(design.slice(0, i + 1))) { + dp[i] = true; + continue; + } + + for (let u of units) { + if (design.slice(i - u.length + 1, i + 1) === u && dp[i - u.length]) { + dp[i] = true; + break; + } + } + } + return dp[n - 1]; + } + + let ans = 0; + for (let design of designs) { + if (possible(design)) { + console.log(design); + ans++; + } + } + + console.log(ans); +});",node:14 +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"const fs = require('fs'); + +const WHITE = ""w""; +const BLUE = ""u""; +const BLACK = ""b""; +const RED = ""r""; +const GREEN = ""g""; + +const INPUT_FILE = ""input.txt""; + +// Read input file +const lines = fs.readFileSync(INPUT_FILE, 'utf8').split('\n'); + +// Read available towels from the first line +const availableTowels = lines[0].trim().split("", ""); + +// Read designs from the lines after the second line +const designs = lines.slice(2).map(line => line.trim()); + +function findFirstPattern(design, startIndex = 0) { + for (let i = design.length; i > 0; i--) { + if (availableTowels.includes(design.slice(startIndex, i))) { + return [i, design.slice(startIndex, i)]; + } + } + return [null, null]; +} + +function findLastPattern(design, endIndex) { + for (let i = 0; i < design.length; i++) { + if (availableTowels.includes(design.slice(i, endIndex))) { + return [i, design.slice(i, endIndex)]; + } + } + return [null, null]; +} + +function findLargestFromStart(design, start = 0) { + let largestPatternMatch = null; + let end = 0; + for (let i = start + 1; i <= design.length; i++) { + const subString = design.slice(start, i); + if (availableTowels.includes(subString)) { + largestPatternMatch = subString; + end = i; + } + } + return [largestPatternMatch, end]; +} + +let canBuildCount = 0; + +function canBuildWord(target, patterns) { + const memo = {}; + + function canBuild(remaining) { + // Base cases + if (!remaining) return true; // Successfully used all letters + if (memo[remaining]) return memo[remaining]; // Already tried this combo + + // Try each pattern at the start of our remaining string + for (const pattern of patterns) { + if (remaining.startsWith(pattern)) { + const newRemaining = remaining.slice(pattern.length); + if (canBuild(newRemaining)) { + memo[remaining] = true; + return true; + } + } + } + + memo[remaining] = false; + return false; + } + + return canBuild(target); +} + +// Loop through designs to check how many can be built with available towels +designs.forEach(design => { + if (canBuildWord(design, availableTowels)) { + canBuildCount += 1; + } +}); + +console.log(canBuildCount); + +// Further processing for patterns +const results = []; +const impossibleDesigns = []; + +designs.forEach(design => { + let patterns = {}; + let result = 0; + let patternFound = false; + + while (true) { + [result, pattern] = findFirstPattern(design, result); + if (!result) { + patternFound = false; + break; + } + patterns[pattern] = (patterns[pattern] || 0) + 1; + if (design.slice(0, result) === design) { + patternFound = true; + break; + } + } + + if (patternFound) { + results.push([design, patterns]); + } else { + patterns = {}; + result = design.length; + patternFound = false; + + while (true) { + [result, pattern] = findLastPattern(design, result); + if (result === null) { + patternFound = false; + break; + } + patterns[pattern] = (patterns[pattern] || 0) + 1; + if (result === 0) { + patternFound = true; + break; + } + } + + if (patternFound) { + results.push([design, patterns]); + } else { + impossibleDesigns.push(design); + } + } +}); + +console.log(""Impossible Designs:"", impossibleDesigns);",node:14 +2024,19,1,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible?",267,"const fs = require('fs'); + +const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n'); + +// Get towel patterns +const towelsLine = input.shift(); +const towels = towelsLine.split(',').map(s => s.trim()); + +// Skip empty lines +while (input.length && input[0].trim() === '') { + input.shift(); +} + +// Get designs +const designs = input.map(s => s.trim()).filter(s => s.length > 0); + +function canForm(design, towels, memo = {}) { + if (design in memo) return memo[design]; + if (design.length === 0) return true; + for (let towel of towels) { + if (design.startsWith(towel)) { + if (canForm(design.slice(towel.length), towels, memo)) { + memo[design] = true; + return true; + } + } + } + memo[design] = false; + return false; +} + +let count = 0; +for (let design of designs) { + if (canForm(design, towels)) { + count++; + } +} + +console.log(count);",node:14 +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"const fs = require('fs'); + +function numPossiblePatterns(pattern, towels, memo) { + if (pattern === """") { + return 1; + } + + if (memo.has(pattern)) { + return memo.get(pattern); + } + + let res = towels.reduce((sum, towel) => { + return sum + (pattern.startsWith(towel) ? numPossiblePatterns(pattern.slice(towel.length), towels, memo) : 0); + }, 0); + + memo.set(pattern, res); + return res; +} + +fs.readFile('input.txt', 'utf8', (err, data) => { + if (err) throw err; + + const lines = data.split('\n'); + const towels = lines[0].split(',').map(s => s.trim()); + const patterns = lines.slice(2); + + console.log( + patterns.reduce((sum, pattern) => sum + numPossiblePatterns(pattern, towels, new Map()), 0) + ); +});",node:14 +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"const fs = require('fs'); + +function buildTowelsTrie(towels) { + const towelsTrie = {}; + towels.forEach(towel => { + let innerDict = towelsTrie; + for (let letter of towel) { + if (!(letter in innerDict)) { + innerDict[letter] = {}; + } + innerDict = innerDict[letter]; + } + innerDict[null] = null; + }); + return towelsTrie; +} + +function patternPossible(pattern, towelsTrie, memo = new Map()) { + if (pattern === """") { + return 1; + } + + if (memo.has(pattern)) { + return memo.get(pattern); + } + + let patternsNeeded = []; + let trie = towelsTrie; + for (let i = 0; i < pattern.length; i++) { + let letter = pattern[i]; + if (letter in trie) { + trie = trie[letter]; + if (null in trie) { + patternsNeeded.push(pattern.slice(i + 1)); + } + } else { + break; + } + } + + let result = patternsNeeded.reduce((sum, subPattern) => sum + patternPossible(subPattern, towelsTrie, memo), 0); + memo.set(pattern, result); + return result; +} + +fs.readFile('input.txt', 'utf8', (err, data) => { + if (err) throw err; + + const inputText = data.split('\n'); + const towels = inputText[0].split(', ').map(s => s.trim()); + const patterns = inputText.slice(2); + + const towelsTrie = buildTowelsTrie(towels); + const totalPatterns = patterns.reduce((sum, pattern) => sum + patternPossible(pattern, towelsTrie), 0); + + console.log(totalPatterns); +});",node:14 +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"const fs = require('fs'); + +function checkCount(towels, pattern, cache) { + if (pattern === """") { + return 1; + } + + const block = cache.get(pattern); + if (block !== undefined) { + return block; + } + + let result = 0; + for (let towel of towels) { + if (pattern.startsWith(towel)) { + result += checkCount(towels, pattern.slice(towel.length), cache); + } + } + + cache.set(pattern, result); + return result; +} + +function getNumAchievablePatterns(towels, patterns) { + return patterns.reduce((sum, pattern) => sum + checkCount(towels, pattern, new Map()), 0); +} + +fs.readFile('day19-2.txt', 'utf8', (err, data) => { + if (err) throw err; + + const lines = data.split('\n'); + let towels = []; + let patterns = []; + for (let line of lines) { + line = line.trim(); + if (line.length === 0) { + continue; + } + if (towels.length === 0) { + towels = line.split(', ').map(s => s.trim()); + } else { + patterns.push(line); + } + } + + console.log(""Number of ways to achieve patterns:"", getNumAchievablePatterns(towels, patterns)); +});",node:14 +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"// solution for https://adventofcode.com/2024/day/19 part 2 + +""use strict"" + +const input = Deno.readTextFileSync(""day19-input.txt"").trim() + +const singles = { } // one letter patterns + +const multiples = { // two or more letter patterns, organized by start + + ""bb"": [ ], + ""bg"": [ ], + ""br"": [ ], + ""bu"": [ ], + ""bw"": [ ], + + ""gb"": [ ], + ""gg"": [ ], + ""gr"": [ ], + ""gu"": [ ], + ""gw"": [ ], + + ""rb"": [ ], + ""rg"": [ ], + ""rr"": [ ], + ""ru"": [ ], + ""rw"": [ ], + + ""ub"": [ ], + ""ug"": [ ], + ""ur"": [ ], + ""uu"": [ ], + ""uw"": [ ], + + ""wb"": [ ], + ""wg"": [ ], + ""wr"": [ ], + ""wu"": [ ], + ""ww"": [ ] +} + +const allTargets = [ ] + +const cache = { } // token: true/false + + +function main() { + + processInput() + + var count = 0 + + for (const target of allTargets) { count += countWays(target) } + + console.log(""the answer is"", count) +} + +function processInput() { + + const sections = input.split(""\n\n"") + + const rawTargets = sections.pop().trim().split(""\n"") + + for (const rawTarget of rawTargets) { allTargets.push(rawTarget.trim()) } + + const patterns = sections.pop().trim().split("", "") + + for (const pattern of patterns) { + + if (pattern.length == 1) { singles[pattern] = true; continue } + + const key = pattern.substr(0, 2) + + multiples[key].push(pattern) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function countWays(target) { + + if (cache[target] != undefined) { return cache[target] } + + if (target.length == 1) { return (singles[target] == true) ? 1 : 0 } + + let ways = 0 + + if (singles[target[0]] == true) { ways += countWays(target.substr(1)) } + + const key = target.substr(0, 2) + + for (const pattern of multiples[key]) { + + if (! target.startsWith(pattern)) { continue } + + const remain = target.replace(pattern, """") + + if (remain == """") { ways += 1; continue } + + ways += countWays(remain) + } + + cache[target] = ways + return ways +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 33ms",node:14 +2024,19,2,"--- Day 19: Linen Layout --- + +Today, The Historians take you up to the hot springs on Gear Island! Very suspiciously, absolutely nothing goes wrong as they begin their careful search of the vast field of helixes. + +Could this finally be your chance to visit the onsen next door? Only one way to find out. + +After a brief conversation with the reception staff at the onsen front desk, you discover that you don't have the right kind of money to pay the admission fee. However, before you can leave, the staff get your attention. Apparently, they've heard about how you helped at the hot springs, and they're willing to make a deal: if you can simply help them arrange their towels, they'll let you in for free! + +Every towel at this onsen is marked with a pattern of colored stripes. There are only a few patterns, but for any particular pattern, the staff can get you as many towels with that pattern as you need. Each stripe can be white (w), blue (u), black (b), red (r), or green (g). So, a towel with the pattern ggr would have a green stripe, a green stripe, and then a red stripe, in that order. (You can't reverse a pattern by flipping a towel upside-down, as that would cause the onsen logo to face the wrong way.) + +The Official Onsen Branding Expert has produced a list of designs - each a long sequence of stripe colors - that they would like to be able to display. You can use any towels you want, but all of the towels' stripes must exactly match the desired design. So, to display the design rgrgr, you could use two rg towels and then an r towel, an rgr towel and then a gr towel, or even a single massive rgrgr towel (assuming such towel patterns were actually available). + +To start, collect together all of the available towel patterns and the list of desired designs (your puzzle input). For example: + +r, wr, b, g, bwu, rb, gb, br + +brwrr +bggr +gbbr +rrbgbr +ubwu +bwurrg +brgr +bbrgwb +The first line indicates the available towel patterns; in this example, the onsen has unlimited towels with a single red stripe (r), unlimited towels with a white stripe and then a red stripe (wr), and so on. + +After the blank line, the remaining lines each describe a design the onsen would like to be able to display. In this example, the first design (brwrr) indicates that the onsen would like to be able to display a black stripe, a red stripe, a white stripe, and then two red stripes, in that order. + +Not all designs will be possible with the available towels. In the above example, the designs are possible or impossible as follows: + +brwrr can be made with a br towel, then a wr towel, and then finally an r towel. +bggr can be made with a b towel, two g towels, and then an r towel. +gbbr can be made with a gb towel and then a br towel. +rrbgbr can be made with r, rb, g, and br. +ubwu is impossible. +bwurrg can be made with bwu, r, r, and g. +brgr can be made with br, g, and r. +bbrgwb is impossible. +In this example, 6 of the eight designs are possible with the available towel patterns. + +To get into the onsen as soon as possible, consult your list of towel patterns and desired designs carefully. How many designs are possible? + +Your puzzle answer was 267. + +--- Part Two --- + +The staff don't really like some of the towel arrangements you came up with. To avoid an endless cycle of towel rearrangement, maybe you should just give them every possible option. + +Here are all of the different ways the above example's designs can be made: + +brwrr can be made in two different ways: b, r, wr, r or br, wr, r. + +bggr can only be made with b, g, g, and r. + +gbbr can be made 4 different ways: + +g, b, b, r +g, b, br +gb, b, r +gb, br +rrbgbr can be made 6 different ways: + +r, r, b, g, b, r +r, r, b, g, br +r, r, b, gb, r +r, rb, g, b, r +r, rb, g, br +r, rb, gb, r +bwurrg can only be made with bwu, r, r, and g. + +brgr can be made in two different ways: b, r, g, r or br, g, r. + +ubwu and bbrgwb are still impossible. + +Adding up all of the ways the towels in this example could be arranged into the desired designs yields 16 (2 + 1 + 4 + 6 + 1 + 2). + +They'll let you into the onsen as soon as you have the list. What do you get if you add up the number of different ways you could make each design?",796449099271652,"const fs = require('fs'); + +const input = fs.readFileSync('input.txt', 'utf-8').trim().split('\n'); + +// Get towel patterns +const towelsLine = input.shift(); +const towels = towelsLine.split(',').map(s => s.trim()); + +// Skip empty lines +while (input.length && input[0].trim() === '') { + input.shift(); +} + +// Get designs +const designs = input.map(s => s.trim()).filter(s => s.length > 0); + +function countWays(design, towels, memo = {}) { + if (design in memo) return memo[design]; + if (design.length === 0) return 1; + let totalWays = 0; + for (let towel of towels) { + if (design.startsWith(towel)) { + totalWays += countWays(design.slice(towel.length), towels, memo); + } + } + memo[design] = totalWays; + return totalWays; +} + +let totalCount = 0; +for (let design of designs) { + totalCount += countWays(design, towels); +} + +console.log(totalCount);",node:14 +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"const fs = require('fs'); + +const Direction = Object.freeze({ + UP: 0, + RIGHT: 1, + DOWN: 2, + LEFT: 3 +}); + +class Position { + constructor(x, y) { + this.x = x; + this.y = y; + } + + toString() { + return `${this.x}_${this.y}`; + } + + equals(other) { + return this.x === other.x && this.y === other.y; + } + + static hash(position) { + return `${position.x}_${position.y}`; + } +} + +class Cheat { + constructor(s, e) { + this.s = s; + this.e = e; + } + + toString() { + return `${this.s.toString()}_${this.e.toString()}`; + } +} + +const space = 0; +const wall = 1; + +function importMatrix(matrixString) { + const matrix = []; + let startPosition = null; + let goalPosition = null; + matrixString.split(""\n"").forEach((line, lineIndex) => { + matrix[lineIndex] = []; + for (let columnIndex = 0; columnIndex < line.length; columnIndex++) { + const tile = line[columnIndex]; + if (tile === ""."") { + matrix[lineIndex].push(space); + } else if (tile === ""#"") { + matrix[lineIndex].push(wall); + } else if (tile === ""S"") { + matrix[lineIndex].push(space); + startPosition = new Position(columnIndex, lineIndex); + } else if (tile === ""E"") { + matrix[lineIndex].push(space); + goalPosition = new Position(columnIndex, lineIndex); + } + } + }); + return [matrix, startPosition, goalPosition]; +} + +function getValidInDirection(currentPosition, direction) { + let p; + switch (direction) { + case Direction.UP: + p = new Position(currentPosition.x, currentPosition.y - 1); + break; + case Direction.LEFT: + p = new Position(currentPosition.x - 1, currentPosition.y); + break; + case Direction.RIGHT: + p = new Position(currentPosition.x + 1, currentPosition.y); + break; + case Direction.DOWN: + p = new Position(currentPosition.x, currentPosition.y + 1); + break; + } + + if (p.x < 0 || p.x >= map[0].length || p.y < 0 || p.y >= map.length) { + return null; + } + return [p, direction]; +} + +function getNeighborsAndCheats(currentPosition) { + const directions = [Direction.LEFT, Direction.RIGHT, Direction.UP, Direction.DOWN]; + const neighborsInMap = directions.map(d => getValidInDirection(currentPosition, d)).filter(Boolean); + const neighbors = []; + const wallsWithDirection = []; + + neighborsInMap.forEach(([p, direction]) => { + if (map[p.y][p.x] === space) { + neighbors.push(p); + } else { + wallsWithDirection.push([p, direction]); + } + }); + + const cheats = []; + wallsWithDirection.forEach(([wd, direction]) => { + const possibleCheat = getValidInDirection(wd, direction); + if (possibleCheat && map[possibleCheat[0].y][possibleCheat[0].x] === space) { + cheats.push(new Cheat(wd, possibleCheat[0])); + } + }); + + return [neighbors, cheats]; +} + +const [map, start, goal] = importMatrix(fs.readFileSync(""20.txt"", ""utf8"")); + +function createTrack() { + const graph = {}; + const cheatsDict = {}; + for (let y = 0; y < map.length; y++) { + for (let x = 0; x < map[y].length; x++) { + if (map[y][x] === wall) continue; + const position = new Position(x, y); + const [neighbors, cheats] = getNeighborsAndCheats(position); + graph[position] = neighbors; + cheatsDict[position] = cheats; + } + } + + const track = {}; + const cheats = {}; + const ignore = new Set(); + let currentPosition = start; + let currentStep = 0; + while (true) { + ignore.add(Position.hash(currentPosition)); + track[currentPosition] = currentStep; + + if (currentPosition.equals(goal)) { + break; + } + + const validCheats = cheatsDict[currentPosition].filter(c => !ignore.has(Position.hash(c.e))); + cheats[currentStep] = validCheats; + + const neighbors = graph[currentPosition]; + for (const neighbor of neighbors) { + if (!ignore.has(Position.hash(neighbor))) { + currentPosition = neighbor; + break; + } + } + + currentStep++; + } + + return [track, cheats, currentStep]; +} + +const [track, cheats, totalSteps] = createTrack(); + +let solution = 0; +for (const step of Object.keys(cheats)) { + cheats[step].forEach(cheat => { + const lengthUpToCheat = Number(step); + const stepAtCheatEnd = track[Position.hash(cheat.e)]; + const resultingLength = lengthUpToCheat + 2 + (totalSteps - stepAtCheatEnd); + const stepsSaved = totalSteps - resultingLength; + if (stepsSaved >= 100) { + solution++; + } + }); +} + +console.log(solution);",node:14 +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"const fs = require('fs'); + +const grid = fs.readFileSync('input.txt', 'utf8').split('\n').map(line => line.split('')); + +function getStart(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]; + } + } + } +} + +function getEnd(grid) { + for (let i = 0; i < grid.length; i++) { + for (let j = 0; j < grid[i].length; j++) { + if (grid[i][j] === 'E') { + return [i, j]; + } + } + } +} + +const start = getStart(grid); +const end = getEnd(grid); + +function getNeighbors(grid, pos) { + const [i, j] = pos; + const neighbors = []; + if (i > 0 && grid[i - 1][j] !== '#') { + neighbors.push([i - 1, j]); + } + if (i < grid.length - 1 && grid[i + 1][j] !== '#') { + neighbors.push([i + 1, j]); + } + if (j > 0 && grid[i][j - 1] !== '#') { + neighbors.push([i, j - 1]); + } + if (j < grid[i].length - 1 && grid[i][j + 1] !== '#') { + neighbors.push([i, j + 1]); + } + return neighbors; +} + +function getRaceTrack(grid, start, end) { + const visited = []; + const queue = [start]; + while (queue.length > 0) { + const pos = queue.shift(); + visited.push(pos); + if (pos[0] === end[0] && pos[1] === end[1]) { + return visited; + } + const neighbors = getNeighbors(grid, pos); + for (const neighbor of neighbors) { + if (!visited.some(v => v[0] === neighbor[0] && v[1] === neighbor[1])) { + queue.push(neighbor); + } + } + } + return []; +} + +function printPath(grid, path) { + const gridCopy = grid.map(line => [...line]); + for (let i = 0; i < Math.min(10, path.length); i++) { + const [iIdx, jIdx] = path[i]; + gridCopy[iIdx][jIdx] = 'X'; + } + gridCopy.forEach(line => { + console.log(line.join('')); + }); +} + +function printCheat(grid, first, second) { + const gridCopy = grid.map(line => [...line]); + gridCopy[first[0]][first[1]] = '1'; + gridCopy[second[0]][second[1]] = '2'; + gridCopy.forEach(line => { + console.log(line.join('')); + }); +} + +function getCheats(path, grid) { + const cheats = {}; + for (let i = 0; i < path.length; i++) { + for (let j = i; j < path.length; j++) { + const [i1, j1] = path[i]; + const [i2, j2] = path[j]; + if ((i1 === i2 && Math.abs(j1 - j2) === 2 && grid[i1][(j1 + j2) / 2] === '#') || + (j1 === j2 && Math.abs(i1 - i2) === 2 && grid[(i1 + i2) / 2][j1] === '#')) { + const savedTime = j - i - 2; + if (!cheats[savedTime]) { + cheats[savedTime] = 1; + } else { + cheats[savedTime]++; + } + } + } + } + return cheats; +} + +const path = getRaceTrack(grid, start, end); +const cheats = getCheats(path, grid); + +let count = 0; +for (const key in cheats) { + if (parseInt(key) >= 100) { + count += cheats[key]; + } +} + +console.log(count);",node:14 +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"// solution for https://adventofcode.com/2024/day/20 part 1 + +""use strict"" + +const input = Deno.readTextFileSync(""day20-input.txt"").trim() + +const map = [ ] + +var width = 0 +var height = 0 + +var homeCell = null + +var goalCell = null + +var bestShortcuts = 0 + + +function main() { + + processInput() + + walk() + + findAllShortcuts() + + console.log(""the answer is"", bestShortcuts) +} + +function processInput() { + + const rawLines = input.split(""\n"") + + let row = -1 + for (const rawLine of rawLines) { + + row += 1 + const mapLine = [ ] + map.push(mapLine) + + let col = -1 + for (const symbol of rawLine.trim()) { + + col += 1 + + const cell = createCell(row, col, symbol) + + if (symbol == ""S"") { homeCell = cell } + if (symbol == ""E"") { goalCell = cell } + + mapLine.push(cell) + } + } + + height = map.length + width = map[0].length +} + +function createCell(row, col, symbol) { + + return { ""row"": row, ""col"": col, ""symbol"": symbol, ""distance"": -1 } +} + +/////////////////////////////////////////////////////////////////////////////// + +function walk() { + + homeCell.distance = 0 + + let cellsToWalk = [ homeCell ] + + while (true) { + + const newCellsToWalk = [ ] + + for (const cell of cellsToWalk) { + + const row = cell.row + const col = cell.col + const distance = cell.distance + 1 + + if (cell == goalCell) { return } // not necessary for my input + + grabCell(row - 1, col, distance, newCellsToWalk) + grabCell(row + 1, col, distance, newCellsToWalk) + grabCell(row, col - 1, distance, newCellsToWalk) + grabCell(row, col + 1, distance, newCellsToWalk) + } + + cellsToWalk = newCellsToWalk + + if (cellsToWalk.length == 0) { return } + } +} + +function grabCell(row, col, distance, newCellsToWalk) { + + if (row < 0) { return } + if (col < 0) { return } + + if (row == height) { return } + if (col == width) { return } + + const cell = map[row][col] + + if (cell.symbol == ""#"") { return } + + if (cell.distance != -1) { return } + + cell.distance = distance + + newCellsToWalk.push(cell) +} + +/////////////////////////////////////////////////////////////////////////////// + +function findAllShortcuts() { + + for (const line of map) { + + for (const cell of line) { + + if (cell.symbol != ""#"") { continue } + + if (cell.row == 0) { continue } + if (cell.col == 0) { continue } + + if (cell.row == height - 1) { continue } + if (cell.col == width - 1) { continue } + + findShortcut(cell) + } + } +} + +function findShortcut(cell) { + + const north = map[cell.row - 1][cell.col] + const south = map[cell.row + 1][cell.col] + const east = map[cell.row][cell.col + 1] + const west = map[cell.row][cell.col - 1] + + const neighbors = [ ] // only cells that are in the path + + if (north.distance != -1) { neighbors.push(north) } + if (south.distance != -1) { neighbors.push(south) } + if (east.distance != -1) { neighbors.push(east) } + if (west.distance != -1) { neighbors.push(west) } + + if (neighbors.length < 2) { return } + + orderByDistance(neighbors) + + const cellBeforeCut = neighbors.shift() + + const distanceBeforeCut = cellBeforeCut.distance + + for (const neighbor of neighbors) { + + const distanceAfterCut = neighbor.distance + + const economy = distanceAfterCut - distanceBeforeCut - 2 + + if (economy >= 100) { bestShortcuts += 1 } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function orderByDistance(list) { + + let n = -1 + + while (true) { + + n += 1 + + const a = list[n] + const b = list[n + 1] + + if (b == undefined) { return } + + if (a.distance < b.distance) { continue } + + list[n] = b + list[n + 1] = a + + n = -1 + } +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 16ms",node:14 +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"const fs = require('fs'); + +// Helper function to parse input and get grid with start and end positions +const parseInput = (filePath) => { + const input = fs.readFileSync(filePath, 'utf-8').split('\n').map(line => [...line.trim()]); + let start = null, end = null; + + input.forEach((line, row) => { + if (line.includes('S')) start = [row, line.indexOf('S')]; + if (line.includes('E')) end = [row, line.indexOf('E')]; + }); + + return { grid: input, start, end }; +}; + +// Function to determine if a given position is within bounds +const isInBounds = (grid, position) => { + const [y, x] = position; + return y >= 0 && y < grid.length && x >= 0 && x < grid[0].length; +}; + +// Function to check neighbors in all four directions +const getNeighbors = (grid, position) => { + const [y, x] = position; + const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + let neighbors = []; + + directions.forEach(([dy, dx]) => { + const newPosition = [y + dy, x + dx]; + if (isInBounds(grid, newPosition) && grid[newPosition[0]][newPosition[1]] !== '#') { + neighbors.push(newPosition); + } + }); + + return neighbors; +}; + +// Function to find shortcuts from the current position +const findShortcuts = (grid, position) => { + const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + const [y, x] = position; + let shortcuts = []; + + directions.forEach(([dy, dx]) => { + if (grid[y + dy] && grid[y + dy][x + dx] === '#') { + const shortcutTo = grid[y + 2 * dy] && grid[y + 2 * dy][x + 2 * dx]; + if (shortcutTo !== '#' && shortcutTo !== '.') { + shortcuts.push(grid[y][x] - shortcutTo - 2); + } + } + }); + + return shortcuts; +}; + +// Function to perform one step in the map +const step = (grid, position, steps) => { + const [y, x] = position; + const directions = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + + for (const [dy, dx] of directions) { + if (grid[y + dy] && grid[y + dy][x + dx] === '.') { + grid[y + dy][x + dx] = steps; + return [y + dy, x + dx]; + } + } + + return position; // No valid move found +}; + +// Main function to simulate the race and collect results +const runRaceSimulation = (filePath) => { + const { grid, start, end } = parseInput(filePath); + let position = start; + let shortcuts = []; + let steps = 0; + + grid[start[0]][start[1]] = 0; + grid[end[0]][end[1]] = '.'; + + + // Traverse the grid to find the path + while (JSON.stringify(position) !== JSON.stringify(end)) { + steps += 1; + shortcuts = [...shortcuts, ...findShortcuts(grid, position)]; + position = step(grid, position, steps); + } + + // Collect shortcuts to the end + shortcuts = [...shortcuts, ...findShortcuts(grid, position)]; + + // Count the occurrences of each shortcut + const counts = shortcuts.reduce((acc, l) => { + acc[l] = (acc[l] || 0) + 1; + return acc; + }, {}); + + // Calculate and print the number of shortcuts with time saved >= 100 + const result = shortcuts.filter(s => s >= 100).length; + console.log(result); +}; + +// Run the simulation with the specified input file +runRaceSimulation('input.txt');",node:14 +2024,20,1,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds?",1307,"const fs = require('fs'); + +function findShortcuts(map, p) { + const [y, x] = p; + const directions = [ + [1, 0], [-1, 0], [0, 1], [0, -1] + ]; + + let shortcuts = []; + + for (const direction of directions) { + if (inDirection(map, p, direction, 1) === '#') { + const shortcutTo = inDirection(map, p, direction, 2); + if (shortcutTo === '#' || shortcutTo === '.') { + continue; + } + shortcuts.push(map[y][x] - shortcutTo - 2); + } + } + + return shortcuts; +} + +function inDirection(map, f, d, count) { + let [y, x] = f; + for (let i = 0; i < count; i++) { + y += d[0]; + x += d[1]; + } + + if (y < 0 || y >= map.length || x < 0 || x >= map[0].length) { + return '#'; + } + return map[y][x]; +} + +function step(map, p, steps) { + const [y, x] = p; + const directions = [ + [y + 1, x], [y - 1, x], [y, x + 1], [y, x - 1] + ]; + + for (const [r, c] of directions) { + if (map[r][c] === '.') { + map[r][c] = steps; + return [r, c]; + } + } + return p; // Shouldn't happen unless there's an error +} + +const map = []; +let start = null; +let end = null; + +const input = fs.readFileSync('input.txt', 'utf-8').split('\n'); + +input.forEach((line, row) => { + line = line.trim(); + map.push([...line]); + + if (line.includes('S')) { + start = [row, line.indexOf('S')]; + } + + if (line.includes('E')) { + end = [row, line.indexOf('E')]; + } +}); + +console.log(`Race from ${start} to ${end}`); +let p = start; +let shortcuts = []; +let steps = 0; +map[start[0]][start[1]] = 0; +map[end[0]][end[1]] = '.'; + +while (JSON.stringify(p) !== JSON.stringify(end)) { + steps += 1; + shortcuts = shortcuts.concat(findShortcuts(map, p)); + p = step(map, p, steps); +} + +// And also shortcuts straight to the end +shortcuts = shortcuts.concat(findShortcuts(map, p)); + +const counts = {}; +shortcuts.forEach(l => { + counts[l] = (counts[l] || 0) + 1; +}); + +const sortedCounts = Object.entries(counts).sort(([a], [b]) => a - b); +sortedCounts.forEach(([l, count]) => { + console.log(`${l}: ${count}`); +}); + +const result = shortcuts.filter(s => s >= 100).length; +console.log(result);",node:14 +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"const fs = require('fs'); + +const parseInput = (filename) => { + const grid = []; + const data = fs.readFileSync(filename, 'utf8').split('\n'); + data.forEach(line => { + grid.push(line.trim().split('')); + }); + return grid; +}; + +const solve1 = (grid, minsave) => { + let si = 0, sj = 0, ei = 0, ej = 0; + const N = grid.length; + const M = grid[0].length; + + const inside = (i, j) => 0 <= i && i < N && 0 <= j && j < M; + + for (let i = 0; i < N; i++) { + for (let j = 0; j < M; j++) { + if (grid[i][j] === 'S') { + si = i; + sj = j; + } else if (grid[i][j] === 'E') { + ei = i; + ej = j; + } + } + } + + const h = [[0, si, sj, 0, 0]]; + const path = []; + const cost = {}; + while (h.length > 0) { + const [c, i, j, pi, pj] = h.pop(); + if (grid[i][j] === ""#"") continue; + path.push([i, j]); + cost[`${i},${j}`] = c; + + if (grid[i][j] === ""E"") break; + + const nxt = [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]; + nxt.forEach(([ni, nj]) => { + if (ni !== pi || nj !== pj) { + h.push([c + 1, ni, nj, i, j]); + } + }); + } + + const savings = {}; + let count = 0; + path.forEach(([i, j]) => { + const nxt = [[i + 2, j], [i - 2, j], [i, j + 2], [i, j - 2]]; + const thru = [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]; + + nxt.forEach(([ni, nj], idx) => { + const [ti, tj] = thru[idx]; + if (!inside(ni, nj) || grid[ni][nj] === '#') return; + if (cost[`${ni},${nj}`] - cost[`${i},${j}`] - 2 >= minsave && grid[ti][tj] === '#') { + savings[`${i},${j},${ni},${nj}`] = cost[`${ni},${nj}`] - cost[`${i},${j}`] - 2; + count += 1; + } + }); + }); + + console.log(`Part One - ${count}`); +}; + +const solve2 = (grid, minsave) => { + let si = 0, sj = 0, ei = 0, ej = 0; + const N = grid.length; + const M = grid[0].length; + + const inside = (i, j) => 0 <= i && i < N && 0 <= j && j < M; + + for (let i = 0; i < N; i++) { + for (let j = 0; j < M; j++) { + if (grid[i][j] === 'S') { + si = i; + sj = j; + } else if (grid[i][j] === 'E') { + ei = i; + ej = j; + } + } + } + + const h = [[0, si, sj, 0, 0]]; + const path = []; + const cost = {}; + while (h.length > 0) { + const [c, i, j, pi, pj] = h.pop(); + if (grid[i][j] === ""#"") continue; + path.push([i, j]); + cost[`${i},${j}`] = c; + + if (grid[i][j] === ""E"") break; + + const nxt = [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]; + nxt.forEach(([ni, nj]) => { + if (ni !== pi || nj !== pj) { + h.push([c + 1, ni, nj, i, j]); + } + }); + } + + const savings = {}; + let count = 0; + path.forEach(([i, j]) => { + for (let step = 2; step <= 20; step++) { + for (let di = 0; di <= step; di++) { + const dj = step - di; + const nxt = [[i + di, j + dj], [i + di, j - dj], [i - di, j + dj], [i - di, j - dj]]; + + nxt.forEach(([ni, nj]) => { + if (!inside(ni, nj) || grid[ni][nj] === '#' || savings[`${i},${j},${ni},${nj}`]) return; + if (cost[`${ni},${nj}`] - cost[`${i},${j}`] - step >= minsave) { + savings[`${i},${j},${ni},${nj}`] = cost[`${ni},${nj}`] - cost[`${i},${j}`] - step; + count += 1; + } + }); + } + } + }); + + console.log(`Part Two - ${count}`); +}; + +// Parse the input grid and solve for both parts +const grid = parseInput('./inputs/day20.txt'); +solve1(grid, 100); +solve2(grid, 100);",node:14 +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"// solution for https://adventofcode.com/2024/day/20 part 2 + +""use strict"" + +const input = Deno.readTextFileSync(""day20-input.txt"").trim() + +const map = [ ] + +var width = 0 +var height = 0 + +var homeCell = null + +var goalCell = null + +const minimumEconomy = 100 + +var bestShortcuts = 0 + + +function main() { + + processInput() + + walk() + + findAllShortcuts() + + console.log(""the answer is"", bestShortcuts) +} + +function processInput() { + + const rawLines = input.split(""\n"") + + let row = -1 + for (const rawLine of rawLines) { + + row += 1 + const mapLine = [ ] + map.push(mapLine) + + let col = -1 + for (const symbol of rawLine.trim()) { + + col += 1 + + const cell = createCell(row, col, symbol) + + if (symbol == ""S"") { homeCell = cell } + if (symbol == ""E"") { goalCell = cell } + + mapLine.push(cell) + } + } + + height = map.length + width = map[0].length +} + +function createCell(row, col, symbol) { + + return { ""row"": row, ""col"": col, ""symbol"": symbol, ""distance"": -1 } +} + +/////////////////////////////////////////////////////////////////////////////// + +function walk() { + + homeCell.distance = 0 + + let cellsToWalk = [ homeCell ] + + while (true) { + + const newCellsToWalk = [ ] + + for (const cell of cellsToWalk) { + + const row = cell.row + const col = cell.col + const distance = cell.distance + 1 + + if (cell == goalCell) { return } // not necessary for my input + + grabCell(row - 1, col, distance, newCellsToWalk) + grabCell(row + 1, col, distance, newCellsToWalk) + grabCell(row, col - 1, distance, newCellsToWalk) + grabCell(row, col + 1, distance, newCellsToWalk) + } + + cellsToWalk = newCellsToWalk + + if (cellsToWalk.length == 0) { return } + } +} + +function grabCell(row, col, distance, newCellsToWalk) { + + if (row < 0) { return } + if (col < 0) { return } + + if (row == height) { return } + if (col == width) { return } + + const cell = map[row][col] + + if (cell.symbol == ""#"") { return } + + if (cell.distance != -1) { return } + + cell.distance = distance + + newCellsToWalk.push(cell) +} + +/////////////////////////////////////////////////////////////////////////////// + +function findAllShortcuts() { + + for (const line of map) { + + for (const cell of line) { + + if (cell.distance != -1) { findShortcut(cell) } + } + } +} + +function findShortcut(baseCell) { + + for (let deltaRow = -20; deltaRow <= 20; deltaRow++) { + + const row = baseCell.row + deltaRow + if (row < 0) { continue } + if (row > height - 1) { return } + + for (let deltaCol = -20; deltaCol <= 20; deltaCol++) { + + const col = baseCell.col + deltaCol + if (col < 0) { continue } + if (col > width - 1) { break } + + const manhattan = Math.abs(deltaRow) + Math.abs(deltaCol) // manhattan distance + + if (manhattan == 0) { continue } + if (manhattan > 20) { continue } + + const cell = map[row][col] + + if (cell.distance == -1) { continue } + + const economy = cell.distance - baseCell.distance - manhattan + + if (economy < minimumEconomy) { continue } + + bestShortcuts += 1 + } + } +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 99ms",node:14 +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"const fs = require('fs'); + +const lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); + +// track +// [ +// [r,c,hacks:[[r,c]]], +// ] +let start, end; +let path = [] + +// add start and end +for (let r = 0; r < lines.length; r++) { + for (let c = 0; c < lines[r].length; c++) { + if (lines[r][c] === 'S') { + start = [r, c]; + } else if (lines[r][c] === 'E') { + end = [r, c]; + } else if (lines[r][c] === '.') { + path.push([r, c]); + } + } +} + +let current = start; +let track = [] + +console.log(start, end); + +while (!(current[0] === end[0] && current[1] === end[1])) { + let adjacent = [ + [[current[0], current[1] + 1], [current[0], current[1] + 2]], + [[current[0], current[1] - 1], [current[0], current[1] - 2]], + [[current[0] - 1, current[1]], [current[0] - 2, current[1]]], + [[current[0] + 1, current[1]], [current[0] + 2, current[1]]], + ]; + let next; + let hacks = []; + for (let [[afr, afc], [nfr, nfc]] of adjacent) { + if (lines[afr][afc] === '.' || lines[afr][afc] === 'E') { + let seen = track.some(i => i[0] === afr && i[1] === afc); + if (!seen) { + next = [afr, afc]; + } + } else if (lines[afr][afc] === '#') { + if (nfr > 0 && nfr < lines.length && nfc > 0 && nfc < lines[0].length) { + if (lines[nfr][nfc] === '.' || lines[nfr][nfc] === 'E') { + let seen = track.some(i => i[0] === nfr && i[1] === nfc); + if (!seen) { + hacks.push([nfr, nfc]); + } + } + } + } + } + track.push([current[0], current[1], hacks]); + if (!next) { + throw 'weird'; + } + current = next; +} +track.push([...end, []]); + +let pico = []; + +for (let i = 0; i < track.length; i++) { + const hacks = track[i][2]; + for (let hack of hacks) { + let index = track.findIndex(t => t[0] === hack[0] && t[1] === hack[1]); + pico.push(index - i - 2); + } +} +console.log('part 1', pico.filter(p => p >= 100).length); + +const distance = (r, c, dr, dc) => { + return Math.abs(r - dr) + Math.abs(c - dc); +} + +let part2 = []; +for (let i = 0; i < track.length - 2; i++) { + for (let j = i + 2; j < track.length; j++) { + const [r, c, {}] = track[i]; + const [dr, dc, {}] = track[j]; + + const d = distance(r, c, dr, dc); + const cutoff = j - i - d; + if (d <= 20 && cutoff >= 100) { + part2.push(cutoff); + } + } +} +console.log(part2.length);",node:14 +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"const fs = require('fs'); + +fs.readFile('input.txt', 'utf8', (err, data) => { + if (err) throw err; + + const inputText = data.split('\n'); + let start = [-1, -1]; + let end = [-1, -1]; + let walls = new Set(); + + for (let row = 0; row < inputText.length; row++) { + for (let col = 0; col < inputText[0].length; col++) { + const cell = inputText[row][col]; + if (cell === 'S') { + start = [row, col]; + } else if (cell === 'E') { + end = [row, col]; + } else if (cell === '#') { + walls.add(`${row},${col}`); + } + } + } + + const moves = [[1, 0], [-1, 0], [0, 1], [0, -1]]; + let noCheatMoveCount = { [`${start[0]},${start[1]}`]: 0 }; + let currentPos = start; + let moveCount = 0; + + while (currentPos[0] !== end[0] || currentPos[1] !== end[1]) { + for (const [rowMove, colMove] of moves) { + const newPos = [currentPos[0] + rowMove, currentPos[1] + colMove]; + const newPosStr = `${newPos[0]},${newPos[1]}`; + if (!walls.has(newPosStr) && !noCheatMoveCount[newPosStr]) { + moveCount += 1; + currentPos = newPos; + noCheatMoveCount[newPosStr] = moveCount; + break; + } + } + } + + let cheatMoves = []; + for (let deltaRow = -20; deltaRow <= 20; deltaRow++) { + for (let deltaCol = -(20 - Math.abs(deltaRow)); deltaCol <= 20 - Math.abs(deltaRow); deltaCol++) { + cheatMoves.push([deltaRow, deltaCol]); + } + } + + let cheats = {}; + + for (let [key, step] of Object.entries(noCheatMoveCount)) { + let [initialRow, initialCol] = key.split(',').map(Number); + + for (let [rowMove, colMove] of cheatMoves) { + const cheatPos = `${initialRow + rowMove},${initialCol + colMove}`; + if (noCheatMoveCount[cheatPos] && noCheatMoveCount[cheatPos] > step + Math.abs(rowMove) + Math.abs(colMove)) { + const saving = noCheatMoveCount[cheatPos] - step - Math.abs(rowMove) - Math.abs(colMove); + cheats[saving] = (cheats[saving] || 0) + 1; + } + } + } + + const result = Object.entries(cheats).reduce((sum, [saving, count]) => { + if (saving >= 100) { + sum += count; + } + return sum; + }, 0); + + console.log(result); +});",node:14 +2024,20,2,"--- Day 20: Race Condition --- + +The Historians are quite pixelated again. This time, a massive, black building looms over you - you're right outside the CPU! + +While The Historians get to work, a nearby program sees that you're idle and challenges you to a race. Apparently, you've arrived just in time for the frequently-held race condition festival! + +The race takes place on a particularly long and twisting code path; programs compete to see who can finish in the fewest picoseconds. The winner even gets their very own mutex! + +They hand you a map of the racetrack (your puzzle input). For example: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +The map consists of track (.) - including the start (S) and end (E) positions (both of which also count as track) - and walls (#). + +When a program runs through the racetrack, it starts at the start position. Then, it is allowed to move up, down, left, or right; each such move takes 1 picosecond. The goal is to reach the end position as quickly as possible. In this example racetrack, the fastest time is 84 picoseconds. + +Because there is only a single path from the start to the end and the programs all go the same speed, the races used to be pretty boring. To make things more interesting, they introduced a new rule to the races: programs are allowed to cheat. + +The rules for cheating are very strict. Exactly once during a race, a program may disable collision for up to 2 picoseconds. This allows the program to pass through walls as if they were regular track. At the end of the cheat, the program must be back on normal track again; otherwise, it will receive a segmentation fault and get disqualified. + +So, a program could complete the course in 72 picoseconds (saving 12 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...12....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Or, a program could complete the course in 64 picoseconds (saving 20 picoseconds) by cheating for the two moves marked 1 and 2: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...12..# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 38 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.####1##.### +#...###.2.#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +This cheat saves 64 picoseconds and takes the program directly to the end: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..21...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Each cheat has a distinct start position (the position where the cheat is activated, just before the first move that is allowed to go through walls) and end position; cheats are uniquely identified by their start position and end position. + +In this example, the total number of cheats (grouped by the amount of time they save) are as follows: + +There are 14 cheats that save 2 picoseconds. +There are 14 cheats that save 4 picoseconds. +There are 2 cheats that save 6 picoseconds. +There are 4 cheats that save 8 picoseconds. +There are 2 cheats that save 10 picoseconds. +There are 3 cheats that save 12 picoseconds. +There is one cheat that saves 20 picoseconds. +There is one cheat that saves 36 picoseconds. +There is one cheat that saves 38 picoseconds. +There is one cheat that saves 40 picoseconds. +There is one cheat that saves 64 picoseconds. +You aren't sure what the conditions of the racetrack will be like, so to give yourself as many options as possible, you'll need a list of the best cheats. How many cheats would save you at least 100 picoseconds? + +Your puzzle answer was 1307. + +--- Part Two --- + +The programs seem perplexed by your list of cheats. Apparently, the two-picosecond cheating rule was deprecated several milliseconds ago! The latest version of the cheating rule permits a single cheat that instead lasts at most 20 picoseconds. + +Now, in addition to all the cheats that were possible in just two picoseconds, many more cheats are possible. This six-picosecond cheat saves 76 picoseconds: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#1#####.#.#.### +#2#####.#.#...# +#3#####.#.###.# +#456.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Because this cheat has the same start and end positions as the one above, it's the same cheat, even though the path taken during the cheat is different: + +############### +#...#...#.....# +#.#.#.#.#.###.# +#S12..#.#.#...# +###3###.#.#.### +###4###.#.#...# +###5###.#.###.# +###6.E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +############### +Cheats don't need to use all 20 picoseconds; cheats can last any amount of time up to and including 20 picoseconds (but can still only end when the program is on normal track). Any cheat time not used is lost; it can't be saved for another cheat later. + +You'll still need a list of the best cheats, but now there are even more to choose between. Here are the quantities of cheats in this example that save 50 picoseconds or more: + +There are 32 cheats that save 50 picoseconds. +There are 31 cheats that save 52 picoseconds. +There are 29 cheats that save 54 picoseconds. +There are 39 cheats that save 56 picoseconds. +There are 25 cheats that save 58 picoseconds. +There are 23 cheats that save 60 picoseconds. +There are 20 cheats that save 62 picoseconds. +There are 19 cheats that save 64 picoseconds. +There are 12 cheats that save 66 picoseconds. +There are 14 cheats that save 68 picoseconds. +There are 12 cheats that save 70 picoseconds. +There are 22 cheats that save 72 picoseconds. +There are 4 cheats that save 74 picoseconds. +There are 3 cheats that save 76 picoseconds. +Find the best cheats using the updated cheating rules. How many cheats would save you at least 100 picoseconds?",986545,"const fs = require('fs'); + +fs.readFile('input20.txt', 'utf8', (err, data) => { + if (err) throw err; + + const input = data.split('\n').map(x => x.trim()); + + const test_data = `############### +#...#...#.....# +#.#.#.#.#.###.# +#S#...#.#.#...# +#######.#.#.### +#######.#.#...# +#######.#.###.# +###..E#...#...# +###.#######.### +#...###...#...# +#.#####.#.###.# +#.#...#.#.#...# +#.#.#.#.#.#.### +#...#...#...### +###############`.split(""\n""); + + // Uncomment the next line to test with test_data + // const input = test_data; + + const map = input.join(""""); + const w = input[0].length; + const h = input.length; + const start = map.indexOf(""S""); + const end = map.indexOf(""E""); + + const printMap = () => { + for (let r = 0; r < h; r++) { + console.log(map.slice(r * w, (r + 1) * w)); + } + }; + + const distances = new Array(w * h).fill(null); + let workingSet = [end]; + let current = 0; + + while (workingSet.length > 0) { + const next = []; + for (let i of workingSet) { + if (distances[i] === null) { + distances[i] = current; + } + const neighbors = [i - 1, i - w, i + 1, i + w]; + for (let neighbor of neighbors) { + if (map[neighbor] !== ""#"" && distances[neighbor] === null) { + next.push(neighbor); + } + } + } + workingSet = next; + current += 1; + } + + const original = distances[start]; + + const getCheats = (cheatLength, limit) => { + let count = 0; + for (let i = 0; i < w * h; i++) { + if (distances[i] === null) continue; + for (let j = i + 1; j < w * h; j++) { + if (distances[j] === null) continue; + const x1 = i % w; + const y1 = Math.floor(i / w); + const x2 = j % w; + const y2 = Math.floor(j / w); + if (Math.abs(x1 - x2) + Math.abs(y1 - y2) <= cheatLength) { + let k = 0; + if (distances[i] > distances[j]) { + k = original - distances[i] + distances[j] + Math.abs(x1 - x2) + Math.abs(y1 - y2); + } else if (distances[i] < distances[j]) { + k = original - distances[j] + distances[i] + Math.abs(x1 - x2) + Math.abs(y1 - y2); + } + if (original - k >= limit) { + count += 1; + } + } + } + } + return count; + }; + + console.log(getCheats(20, 100)); +});",node:14 +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"const fs = require('fs'); + +// Read the input file +const input = fs.readFileSync('input.txt', { encoding: ""utf8"", flag: ""r"" }); +const keypadCodes = input.split('\n'); + +// Keypad and Directional Pad definitions +const keypad = [ + ['7', '8', '9'], + ['4', '5', '6'], + ['1', '2', '3'], + [null, '0', 'A'], +]; + +const dirpad = [ + [null, '^', 'A'], + ['<', 'v', '>'] +]; + +// Function to count occurrences of characters in a string +const count = (str) => { + let countObj = {}; + for (let char of str) { + countObj[char] = (countObj[char] || 0) + 1; + } + return countObj; +}; + +// Function to calculate all shortest best paths on the grid +const allShortestBest = (start, grid) => { + let pathsObj = {}; + let seen = new Set(); + seen.add(start.join('|')); + let startVal = grid[start[0]][start[1]]; + let queue = [[[start, '', startVal]]]; + + const nextStep = ([r, c], grid) => { + return [[r - 1, c, '^'], [r, c + 1, '>'], [r + 1, c, 'v'], [r, c - 1, '<']].filter(([nr, nc, nd]) => + grid?.[nr]?.[nc] !== undefined && !seen.has(`${nr}|${nc}`) && !!grid?.[nr]?.[nc] + ).map(([nr, nc, nd]) => [[nr, nc], nd].concat(grid[nr][nc])); + }; + + while (queue.length > 0) { + let nextQueue = []; + let queueSeen = []; + + queue.forEach((path) => { + let last = [point, dir, val] = path.at(-1); + let next = nextStep(point, grid); + + next.forEach(([np, nd, nv]) => { + queueSeen.push(np.join('|')); + let newPath = path.concat([[np, nd, nv]]); + pathsObj[nv] ? pathsObj[nv].push(newPath.map((x) => x[1]).join('')) : pathsObj[nv] = [newPath.map((x) => x[1]).join('')]; + nextQueue.push(newPath); + }); + }); + + queueSeen.forEach((x) => seen.add(x)); + queue = nextQueue; + } + + let bestPaths = {}; + + Object.entries(pathsObj).forEach(([k, paths]) => { + if (paths.length === 1) { + bestPaths[`${startVal}${k}`] = `${paths[0]}A`; + + if (startVal === 'A') bestPaths[k] = `${paths[0]}A`; + } else { + let order = ''; + const pathscore = (path) => { + let split = path.split(''); + + return split.slice(0, -1).map((y, yx) => { + let score = 0; + if (y !== split[yx + 1]) score += 10; + + if (order.indexOf(split[yx + 1]) < order.indexOf(y)) score += 5; + + return score; + }).reduce((a, b) => a + b, 0); + }; + + let scores = paths.map((x) => [pathscore(x), x]).sort((a, c) => a[0] - c[0]); + + bestPaths[`${startVal}${k}`] = `${scores[0][1]}A`; + + if (startVal === 'A') bestPaths[k] = `${scores[0][1]}A`; + } + }); + return bestPaths; +}; + +let numpadDirs = Object.assign(...keypad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], keypad))); + +let dirs = Object.assign(...dirpad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], dirpad))); +dirs['A'] = 'A'; +dirs['AA'] = 'A'; +dirs['<<'] = 'A'; +dirs['>>'] = 'A'; +dirs['^^'] = 'A'; +dirs['vv'] = 'A'; + +const codes = keypadCodes.map((x) => [''].concat(x.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1)).map((x) => x.map((y) => numpadDirs[y])); // First keyboard, array of button presses e.g. ['^^A','vvvA'] for example + +// Function to calculate the minimum presses required +const minPresses = (keypadCodes, dircodes, keyboards) => { + let keypadNums = keypadCodes.map((x) => parseInt(x.slice(0, -1))); + let targetDepth = keyboards - 1; + let result = 0; + + for (const [index, code] of dircodes.entries()) { + let countObj = count(code); + + for (let i = 0; i < targetDepth; i++) { + let newCountObj = {}; + for (const [key, val] of Object.entries(countObj)) { + if (key.length === 1) { + let newKey = dirs[key]; + + newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; + } else { + let keySplit = [''].concat(key.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1); + + keySplit.forEach((sKey) => { + let newKey = dirs[sKey]; + newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; + }); + } + } + countObj = newCountObj; + } + + result += (Object.entries(countObj).map(([k, v]) => k.length * v).reduce((a, b) => a + b, 0) * keypadNums[index]); + } + return result; +}; + +// Performance tracking and calculation +const t0 = performance.now(); +let p1 = minPresses(keypadCodes, codes, 3); +const t1 = performance.now(); + + +console.log('Part 1 answer is ', p1, t1 - t0, 'ms'); + +// Old list of hardcoded directions (commented out for clarity) +const olddirs = { + '<': 'v<': 'vA', + 'A': 'A', + '<^': '>^A', + 'A', + '<>': '>>A', + '>^A', + '^<': 'v': 'v>A', + '^A': '>A', + 'v<': '': '>A', + 'vA': '^>A', + '><': '<v': '^': '<^A', + '>A': '^A', + 'A<': 'v<': 'vA', + '<<': 'A', + 'vv': 'A', + '^^': 'A', + '>>': 'A', + 'AA': 'A' +};",node:14 +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,,node:14 +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,,node:14 +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,,node:14 +2024,21,1,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",157908,"const fs = require('fs'); + +const keypadSequences = fs.readFileSync('input.txt', 'utf8').split('\n'); + +const keypad = { + '7': [0, 0], '8': [0, 1], '9': [0, 2], + '4': [1, 0], '5': [1, 1], '6': [1, 2], + '1': [2, 0], '2': [2, 1], '3': [2, 2], + '#': [3, 0], '0': [3, 1], 'A': [3, 2] +}; +const keypadBadPosition = [3, 0]; +const startKeypad = [3, 2]; + +const directionalpad = { + '#': [0, 0], '^': [0, 1], 'A': [0, 2], + '<': [1, 0], 'v': [1, 1], '>': [1, 2] +}; +const directionalpadBadPosition = [0, 0]; +const startdirectionalpad = [0, 2]; + +const getNumericPart = (code) => { + return code.split('').filter(elem => /\d/.test(elem)).join(''); +}; + +const getdirections = (drow, dcol) => { + let res = []; + if (drow > 0) { + res.push('v'.repeat(drow)); + } else if (drow < 0) { + res.push('^'.repeat(Math.abs(drow))); + } + if (dcol > 0) { + res.push('>'.repeat(dcol)); + } else if (dcol < 0) { + res.push('<'.repeat(Math.abs(dcol))); + } + return res.join(''); +}; + +const getPossiblePermutations = (pos, directions, position) => { + const perms = new Set(permutations(directions)); + let validPerms = []; + perms.forEach(perm => { + if (validatepath(pos, perm, position)) { + validPerms.push(perm.join('')); + } + }); + return validPerms; +}; + +const validatepath = (pos, directions, position) => { + let _pos = pos; + for (let direction of directions) { + if (direction === 'v') { + _pos = [_pos[0] + 1, _pos[1]]; + } else if (direction === '^') { + _pos = [_pos[0] - 1, _pos[1]]; + } else if (direction === '>') { + _pos = [_pos[0], _pos[1] + 1]; + } else if (direction === '<') { + _pos = [_pos[0], _pos[1] - 1]; + } + + if (_pos.toString() === position.toString()) { + return false; + } + } + return true; +}; + +const getDirectionToWriteCode = (input) => { + let pos = startKeypad; + let result = []; + for (let elem of input) { + let nextPos = keypad[elem]; + let drow = nextPos[0] - pos[0]; + let dcol = nextPos[1] - pos[1]; + let directions = getdirections(drow, dcol); + let validPaths = getPossiblePermutations(pos, directions, keypadBadPosition); + if (result.length === 0) { + for (let path of validPaths) { + result.push(path + 'A'); + } + } else { + let temp = []; + for (let res of result) { + for (let path of validPaths) { + temp.push(res + path + 'A'); + } + } + result = temp; + } + pos = nextPos; + } + return result; +}; + +const getDirectionToWriteDirection = (input) => { + let pos = startdirectionalpad; + let result = []; + for (let elem of input) { + let nextPos = directionalpad[elem]; + let drow = nextPos[0] - pos[0]; + let dcol = nextPos[1] - pos[1]; + let directions = getdirections(drow, dcol); + let validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition); + if (result.length === 0) { + for (let path of validPaths) { + result.push(path + 'A'); + } + } else { + let temp = []; + for (let res of result) { + for (let path of validPaths) { + temp.push(res + path + 'A'); + } + } + result = temp; + } + pos = nextPos; + } + + let minLength = Math.min(...result.map(r => r.length)); + return result.filter(r => r.length === minLength); +}; + +const getDirectionToWriteDirectionSample = (input) => { + let pos = startdirectionalpad; + let result = []; + for (let elem of input) { + let nextPos = directionalpad[elem]; + let drow = nextPos[0] - pos[0]; + let dcol = nextPos[1] - pos[1]; + let directions = getdirections(drow, dcol); + let validPaths = getPossiblePermutations(pos, directions, directionalpadBadPosition)[0]; + result.push(validPaths); + result.push('A'); + pos = nextPos; + } + return result.join(''); +}; + +const calculateComplexity = (code) => { + let sol1 = getDirectionToWriteCode(code); + let sol2 = sol1.flatMap(sol => getDirectionToWriteDirection(sol)); + let sol3 = sol2.map(elem => getDirectionToWriteDirectionSample(elem)); + console.log(sol3[0]); + console.log(sol2[0]); + console.log(sol1[0]); + console.log(code); + let minLength = Math.min(...sol3.map(r => r.length)); + let num = getNumericPart(code); + console.log(`Code: Numeric: ${num}, minimum length: ${minLength}`); + return minLength * parseInt(num); +}; + +let total = 0; +keypadSequences.forEach(code => { + let score = calculateComplexity(code); + total += score; + console.log(); +}); +console.log(total); + +// Helper function to generate permutations (equivalent to Python's itertools.permutations) +function permutations(arr) { + let result = []; + const permute = (arr, current = []) => { + if (arr.length === 0) { + result.push(current); + return; + } + for (let i = 0; i < arr.length; i++) { + let newArr = [...arr]; // Correctly copy the array + newArr.splice(i, 1); // Remove the element at index i + permute(newArr, current.concat(arr[i])); // Continue recursion + } + }; + permute(arr); + return result; +}",node:14 +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,"const fs = require('fs'); + +// Read the input file +const input = fs.readFileSync('input.txt', { encoding: ""utf8"", flag: ""r"" }); +const keypadCodes = input.split('\n'); + +// Keypad and Directional Pad definitions +const keypad = [ + ['7', '8', '9'], + ['4', '5', '6'], + ['1', '2', '3'], + [null, '0', 'A'], +]; + +const dirpad = [ + [null, '^', 'A'], + ['<', 'v', '>'] +]; + +// Function to count occurrences of characters in a string +const count = (str) => { + let countObj = {}; + for (let char of str) { + countObj[char] = (countObj[char] || 0) + 1; + } + return countObj; +}; + +// Function to calculate all shortest best paths on the grid +const allShortestBest = (start, grid) => { + let pathsObj = {}; + let seen = new Set(); + seen.add(start.join('|')); + let startVal = grid[start[0]][start[1]]; + let queue = [[[start, '', startVal]]]; + + const nextStep = ([r, c], grid) => { + return [[r - 1, c, '^'], [r, c + 1, '>'], [r + 1, c, 'v'], [r, c - 1, '<']].filter(([nr, nc, nd]) => + grid?.[nr]?.[nc] !== undefined && !seen.has(`${nr}|${nc}`) && !!grid?.[nr]?.[nc] + ).map(([nr, nc, nd]) => [[nr, nc], nd].concat(grid[nr][nc])); + }; + + while (queue.length > 0) { + let nextQueue = []; + let queueSeen = []; + + queue.forEach((path) => { + let last = [point, dir, val] = path.at(-1); + let next = nextStep(point, grid); + + next.forEach(([np, nd, nv]) => { + queueSeen.push(np.join('|')); + let newPath = path.concat([[np, nd, nv]]); + pathsObj[nv] ? pathsObj[nv].push(newPath.map((x) => x[1]).join('')) : pathsObj[nv] = [newPath.map((x) => x[1]).join('')]; + nextQueue.push(newPath); + }); + }); + + queueSeen.forEach((x) => seen.add(x)); + queue = nextQueue; + } + + let bestPaths = {}; + + Object.entries(pathsObj).forEach(([k, paths]) => { + if (paths.length === 1) { + bestPaths[`${startVal}${k}`] = `${paths[0]}A`; + + if (startVal === 'A') bestPaths[k] = `${paths[0]}A`; + } else { + let order = ''; + const pathscore = (path) => { + let split = path.split(''); + + return split.slice(0, -1).map((y, yx) => { + let score = 0; + if (y !== split[yx + 1]) score += 10; + + if (order.indexOf(split[yx + 1]) < order.indexOf(y)) score += 5; + + return score; + }).reduce((a, b) => a + b, 0); + }; + + let scores = paths.map((x) => [pathscore(x), x]).sort((a, c) => a[0] - c[0]); + + bestPaths[`${startVal}${k}`] = `${scores[0][1]}A`; + + if (startVal === 'A') bestPaths[k] = `${scores[0][1]}A`; + } + }); + return bestPaths; +}; + +let numpadDirs = Object.assign(...keypad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], keypad))); + +let dirs = Object.assign(...dirpad.flatMap((x, ix) => x.map((y, yx) => [ix, yx, y])).filter((z) => z[2] !== null).map(([r, c, v]) => allShortestBest([r, c], dirpad))); +dirs['A'] = 'A'; +dirs['AA'] = 'A'; +dirs['<<'] = 'A'; +dirs['>>'] = 'A'; +dirs['^^'] = 'A'; +dirs['vv'] = 'A'; + +const codes = keypadCodes.map((x) => [''].concat(x.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1)).map((x) => x.map((y) => numpadDirs[y])); // First keyboard, array of button presses e.g. ['^^A','vvvA'] for example + +// Function to calculate the minimum presses required +const minPresses = (keypadCodes, dircodes, keyboards) => { + let keypadNums = keypadCodes.map((x) => parseInt(x.slice(0, -1))); + let targetDepth = keyboards - 1; + let result = 0; + + for (const [index, code] of dircodes.entries()) { + let countObj = count(code); + + for (let i = 0; i < targetDepth; i++) { + let newCountObj = {}; + for (const [key, val] of Object.entries(countObj)) { + if (key.length === 1) { + let newKey = dirs[key]; + + newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; + } else { + let keySplit = [''].concat(key.split('')).map((x, ix, arr) => `${x}${arr[ix + 1]}`).slice(0, -1); + + keySplit.forEach((sKey) => { + let newKey = dirs[sKey]; + newCountObj[newKey] ? newCountObj[newKey] += val : newCountObj[newKey] = val; + }); + } + } + countObj = newCountObj; + } + + result += (Object.entries(countObj).map(([k, v]) => k.length * v).reduce((a, b) => a + b, 0) * keypadNums[index]); + } + return result; +}; + +// Performance tracking and calculation +const t0 = performance.now(); +let p1 = minPresses(keypadCodes, codes, 3); +const t1 = performance.now(); + +let p2 = minPresses(keypadCodes, codes, 26); +const t2 = performance.now(); + +console.log('Part 1 answer is ', p1, t1 - t0, 'ms'); +console.log('Part 2 answer is ', p2, t2 - t1, 'ms'); + +// Old list of hardcoded directions (commented out for clarity) +const olddirs = { + '<': 'v<': 'vA', + 'A': 'A', + '<^': '>^A', + 'A', + '<>': '>>A', + '>^A', + '^<': 'v': 'v>A', + '^A': '>A', + 'v<': '': '>A', + 'vA': '^>A', + '><': '<v': '^': '<^A', + '>A': '^A', + 'A<': 'v<': 'vA', + '<<': 'A', + 'vv': 'A', + '^^': 'A', + '>>': 'A', + 'AA': 'A' +};",node:14 +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,,node:14 +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,,node:14 +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,,node:14 +2024,21,2,"--- Day 21: Keypad Conundrum --- + +As you teleport onto Santa's Reindeer-class starship, The Historians begin to panic: someone from their search party is missing. A quick life-form scan by the ship's computer reveals that when the missing Historian teleported, he arrived in another part of the ship. + +The door to that area is locked, but the computer can't open it; it can only be opened by physically typing the door codes (your puzzle input) on the numeric keypad on the door. + +The numeric keypad has four rows of buttons: 789, 456, 123, and finally an empty gap followed by 0A. Visually, they are arranged like this: + ++---+---+---+ +| 7 | 8 | 9 | ++---+---+---+ +| 4 | 5 | 6 | ++---+---+---+ +| 1 | 2 | 3 | ++---+---+---+ + | 0 | A | + +---+---+ +Unfortunately, the area outside the door is currently depressurized and nobody can go near the door. A robot needs to be sent instead. + +The robot has no problem navigating the ship and finding the numeric keypad, but it's not designed for button pushing: it can't be told to push a specific button directly. Instead, it has a robotic arm that can be controlled remotely via a directional keypad. + +The directional keypad has two rows of buttons: a gap / ^ (up) / A (activate) on the first row and < (left) / v (down) / > (right) on the second row. Visually, they are arranged like this: + + +---+---+ + | ^ | A | ++---+---+---+ +| < | v | > | ++---+---+---+ +When the robot arrives at the numeric keypad, its robotic arm is pointed at the A button in the bottom right corner. After that, this directional keypad remote control must be used to maneuver the robotic arm: the up / down / left / right buttons cause it to move its arm one button in that direction, and the A button causes the robot to briefly move forward, pressing the button being aimed at by the robotic arm. + +For example, to make the robot type 029A on the numeric keypad, one sequence of inputs on the directional keypad you could use is: + +< to move the arm from A (its initial position) to 0. +A to push the 0 button. +^A to move the arm to the 2 button and push it. +>^^A to move the arm to the 9 button and push it. +vvvA to move the arm to the A button and push it. +In total, there are three shortest possible sequences of button presses on this directional keypad that would cause the robot to type 029A: ^^AvvvA, ^AvvvA, and AvvvA. + +Unfortunately, the area containing this directional keypad remote control is currently experiencing high levels of radiation and nobody can go near it. A robot needs to be sent instead. + +When the robot arrives at the directional keypad, its robot arm is pointed at the A button in the upper right corner. After that, a second, different directional keypad remote control is used to control this robot (in the same way as the first robot, except that this one is typing on a directional keypad instead of a numeric keypad). + +There are multiple shortest possible sequences of directional keypad button presses that would cause this robot to tell the first robot to type 029A on the door. One such sequence is v<>^AAvA<^AA>A^A. + +Unfortunately, the area containing this second directional keypad remote control is currently -40 degrees! Another robot will need to be sent to type on that directional keypad, too. + +There are many shortest possible sequences of directional keypad button presses that would cause this robot to tell the second robot to tell the first robot to eventually type 029A on the door. One such sequence is >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A. + +Unfortunately, the area containing this third directional keypad remote control is currently full of Historians, so no robots can find a clear path there. Instead, you will have to type this sequence yourself. + +Were you to choose this sequence of button presses, here are all of the buttons that would be pressed on your directional keypad, the two robots' directional keypads, and the numeric keypad: + +>^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +v<>^AAvA<^AA>A^A +^^AvvvA +029A +In summary, there are the following keypads: + +One directional keypad that you are using. +Two directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +It is important to remember that these robots are not designed for button pushing. In particular, if a robot arm is ever aimed at a gap where no button is present on the keypad, even for an instant, the robot will panic unrecoverably. So, don't do that. All robots will initially aim at the keypad's A key, wherever it is. + +To unlock the door, five codes will need to be typed on its numeric keypad. For example: + +029A +980A +179A +456A +379A +For each of these, here is a shortest sequence of button presses you could type to cause the desired code to be typed on the numeric keypad: + +029A: >^AvAA<^A>A>^AvA^A^A^A>AAvA^AA>^AAAvA<^A>A +980A: >^AAAvA^A>^AvAA<^A>AA>^AAAvA<^A>A^AA +179A: >^A>^AAvAA<^A>A>^AAvA^A^AAAA>^AAAvA<^A>A +456A: >^AA>^AAvAA<^A>A^AA^AAA>^AAvA<^A>A +379A: >^AvA^A>^AAvA<^A>AAvA^A^AAAA>^AAAvA<^A>A +The Historians are getting nervous; the ship computer doesn't remember whether the missing Historian is trapped in the area containing a giant electromagnet or molten lava. You'll need to make sure that for each of the five codes, you find the shortest sequence of button presses necessary. + +The complexity of a single code (like 029A) is equal to the result of multiplying these two values: + +The length of the shortest sequence of button presses you need to type on your directional keypad in order to cause the code to be typed on the numeric keypad; for 029A, this would be 68. +The numeric part of the code (ignoring leading zeroes); for 029A, this would be 29. +In the above example, complexity of the five codes can be found by calculating 68 * 29, 60 * 980, 68 * 179, 64 * 456, and 64 * 379. Adding these together produces 126384. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list? + +Your puzzle answer was 157908. + +--- Part Two --- + +Just as the missing Historian is released, The Historians realize that a second member of their search party has also been missing this entire time! + +A quick life-form scan reveals the Historian is also trapped in a locked area of the ship. Due to a variety of hazards, robots are once again dispatched, forming another chain of remote control keypads managing robotic-arm-wielding robots. + +This time, many more robots are involved. In summary, there are the following keypads: + +One directional keypad that you are using. +25 directional keypads that robots are using. +One numeric keypad (on a door) that a robot is using. +The keypads form a chain, just like before: your directional keypad controls a robot which is typing on a directional keypad which controls a robot which is typing on a directional keypad... and so on, ending with the robot which is typing on the numeric keypad. + +The door codes are the same this time around; only the number of robots and directional keypads has changed. + +Find the fewest number of button presses you'll need to perform in order to cause the robot in front of the door to type each code. What is the sum of the complexities of the five codes on your list?",196910339808654,,node:14 +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"const fs = require('fs'); + +// Step transformation function +function transformNumber(secret) { + let transformed = secret; + + // Perform the 2000 transformations + for (let i = 0; i < 2000; i++) { + transformed ^= (transformed * 64) & 0xFFFFFF; + transformed ^= Math.floor(transformed / 32) & 0xFFFFFF; + transformed ^= (transformed * 2048) & 0xFFFFFF; + } + + return transformed; +} + +// Read the file input as a string and split it by lines, then convert to numbers +function processInput(filePath) { + const data = fs.readFileSync(filePath, 'utf-8'); + const numbers = data.split('\n').map(Number); + return numbers; +} + +// Calculate the total by processing each number +function calculateTotal(filePath) { + const numbers = processInput(filePath); + let totalSum = 0; + + // Process each number and accumulate the transformed values + numbers.forEach(secret => { + totalSum += transformNumber(secret); + }); + + return totalSum; +} + +// Run the main function +function main() { + const result = calculateTotal('input.txt'); + console.log(result); +} + +main();",node:14 +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"const fs = require('fs'); + +// Function to generate secrets after 2000 iterations +function generateSecrets(secret) { + let result = []; + for (let i = 0; i < 2000; i++) { + secret ^= (secret << 6) & 0xFFFFFF; + secret ^= (secret >> 5) & 0xFFFFFF; + secret ^= (secret << 11) & 0xFFFFFF; + result.push(secret); + } + return result; +} + +// Read the input file and parse into an array of numbers +const input = fs.readFileSync(""input.txt"", 'utf-8').trim().split(""\n"").map(Number); + +// Map each number in the input array to its secret numbers after 2000 steps +const secrets = input.map(generateSecrets); + +// Calculate the total sum of the last secret number from each sequence +let totalSum = 0; +for (const secretArray of secrets) { + totalSum += secretArray[secretArray.length - 1]; +} + +// Output the result +console.log(totalSum);",node:14 +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"const fs = require('fs'); + +const hsh = function* (secret) { + for (let i = 0; i < 2000; i++) { + secret ^= (secret << 6) & 0xFFFFFF; + secret ^= (secret >> 5) & 0xFFFFFF; + secret ^= (secret << 11) & 0xFFFFFF; + yield secret; + } +}; + +const ns = fs.readFileSync(""input.txt"", 'utf-8').trim().split(""\n"").map(Number); + +const secrets = ns.map((num) => Array.from(hsh(num))); + +// Part 1 +const total = secrets.reduce((sum, secret) => sum + secret[secret.length - 1], 0); +console.log(total);",node:14 +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"// solution for https://adventofcode.com/2024/day/22 part 1 + +""use strict"" + +const input = Deno.readTextFileSync(""day22-input.txt"").trim() + +const allNumbers = [ ] // BigInts + + +function main() { + + processInput() + + let sum = BigInt(0) + + for (const secret of allNumbers) { sum += processSecretNumber(secret) } + + console.log(""the answer is"", sum) +} + +function processInput() { + + const rawLines = input.split(""\n"") + + for (const rawLine of rawLines) { + + const number = BigInt(rawLine.trim()) + + allNumbers.push(number) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function processSecretNumber(secret) { + + for (let n = 0; n < 2000; n++) { + + secret = processSecretNumberOnce(secret) + } + return secret +} + +function processSecretNumberOnce(secret) { // expecting BigInt + + const a = secret * BigInt(64) + const b = a ^ secret + const step1 = b % BigInt(16777216) + + const c = step1 / BigInt(32) // BigInt automatically rounds down + const d = c ^ step1 + const step2 = d % BigInt(16777216) + + const e = step2 * BigInt(2048) + const f = e ^ step2 + const step3 = f % BigInt(16777216) + + return step3 +} + +/////////////////////////////////////////////////////////////////////////////// + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 55ms",node:14 +2024,22,1,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer?",15335183969,"const fs = require(""fs""); +const data = fs.readFileSync(""input.txt"",""utf8"").trim().split(""\n"").map(Number); + +function nextSecret(s) { + // Step 1 + let m = s * 64; + s ^= m; + s &= 0xFFFFFF; // modulo 16777216 + + // Step 2 + m = s >>> 5; // integer division by 32 + s ^= m; + s &= 0xFFFFFF; + + // Step 3 + m = s * 2048; + s ^= m; + s &= 0xFFFFFF; + + return s; +} + +function get2000thSecret(start) { + let s = start; + for (let i = 0; i < 2000; i++) { + s = nextSecret(s); + } + return s; +} + +const result = data.reduce((sum, val) => sum + get2000thSecret(val), 0); +console.log(result);",node:14 +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"const fs = require('fs'); + +function* hsh(secret) { + for (let i = 0; i < 2000; i++) { + secret ^= (secret << 6) & 0xFFFFFF; + secret ^= (secret >> 5) & 0xFFFFFF; + secret ^= (secret << 11) & 0xFFFFFF; + yield secret; + } +} + +function loadFile(filename) { + const data = fs.readFileSync(filename, 'utf-8'); + return data.split('\n').map(Number); +} + +function calculate() { + const ns = loadFile(""input.txt""); + + const result = {}; + for (let n of ns) { + const ss = [...hsh(n)].map(s => s % 10); + const diffs = ss.slice(1).map((s, i) => s - ss[i]); + const changes = new Set(); + + for (let i = 0; i < 1996; i++) { + const change = JSON.stringify(diffs.slice(i, i + 4)); + if (!changes.has(change)) { + changes.add(change); + if (!result[change]) result[change] = 0; + result[change] += ss[i + 4]; + } + } + } + + const max = Math.max(...Object.values(result)); + console.log(max); +} + +calculate();",node:14 +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"const fs = require('fs'); + +// Generate hash sequence from a given secret +function* generateHash(secret) { + for (let i = 0; i < 2000; i++) { + secret ^= (secret << 6) & 0xFFFFFF; + secret ^= (secret >> 5) & 0xFFFFFF; + secret ^= (secret << 11) & 0xFFFFFF; + yield secret; + } +} + +// Read and parse the input file, returning an array of numbers +function readInputFile(file) { + const fileData = fs.readFileSync(file, 'utf-8'); + return fileData.split('\n').map(Number); +} + +// Main calculation function +function findMaxBananas() { + const numbers = readInputFile(""input.txt""); + + let patterns = {}; // Store the patterns and their corresponding sums + + for (let number of numbers) { + // Generate hash sequence and calculate prices + const hashSequence = [...generateHash(number)].map(hash => hash % 10); + const priceDifferences = hashSequence.slice(1).map((currentPrice, idx) => currentPrice - hashSequence[idx]); + + const uniqueChanges = new Set(); + + // Track unique 4-change sequences + for (let i = 0; i < 1996; i++) { + const changesSequence = JSON.stringify(priceDifferences.slice(i, i + 4)); + + if (!uniqueChanges.has(changesSequence)) { + uniqueChanges.add(changesSequence); + if (!patterns[changesSequence]) patterns[changesSequence] = 0; + patterns[changesSequence] += hashSequence[i + 4]; // Add corresponding price to the sum + } + } + } + + // Find the maximum sum from all patterns + const maxSum = Math.max(...Object.values(patterns)); + console.log(maxSum); // Output the result +} + +findMaxBananas();",node:14 +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"const fs = require(""fs""); +const data = fs.readFileSync(""input.txt"",""utf8"").trim().split(""\n"").map(Number); + +function nextSecret(s) { + let m = s * 64; + s ^= m; + s &= 0xFFFFFF; + + m = s >>> 5; + s ^= m; + s &= 0xFFFFFF; + + m = s * 2048; + s ^= m; + s &= 0xFFFFFF; + + return s; +} + +// Precompute prices and earliest 4-change sequences for each buyer +const buyers = data.map(start => { + let secrets = [start]; + for (let i = 0; i < 2000; i++) { + secrets.push(nextSecret(secrets[secrets.length - 1])); + } + let prices = secrets.map(s => s % 10); + let changesMap = new Map(); + for (let i = 0; i < 2000; i++) { + // four consecutive changes, if i+3 < 2000 + if (i + 3 < 2000) { + let c1 = prices[i+1] - prices[i]; + let c2 = prices[i+2] - prices[i+1]; + let c3 = prices[i+3] - prices[i+2]; + let c4 = prices[i+4] - prices[i+3]; + let key = `${c1},${c2},${c3},${c4}`; + if (!changesMap.has(key)) { + changesMap.set(key, i); + } + } + } + return { prices, changesMap }; +}); + +// Try all possible 4-change sequences [-9..9] +let bestSum = 0; +for (let a = -9; a <= 9; a++) { + for (let b = -9; b <= 9; b++) { + for (let c = -9; c <= 9; c++) { + for (let d = -9; d <= 9; d++) { + let seqKey = `${a},${b},${c},${d}`; + let sumBananas = 0; + for (let buyer of buyers) { + let idx = buyer.changesMap.get(seqKey); + if (idx !== undefined) { + // sell at prices[idx+4] + sumBananas += buyer.prices[idx+4]; + } + } + if (sumBananas > bestSum) bestSum = sumBananas; + } + } + } +} + +console.log(bestSum);// solution for https://adventofcode.com/2024/day/22 part 2",node:14 +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"const fs = require('fs'); + +// Step transformation function for hashing +function* hsh(secret) { + for (let i = 0; i < 2000; i++) { + secret ^= (secret << 6) & 0xFFFFFF; + secret ^= Math.floor(secret / 32) & 0xFFFFFF; + secret ^= (secret * 2048) & 0xFFFFFF; + yield secret; + } +} + +// Function to read and parse the input from the file +function readInput(filePath) { + const data = fs.readFileSync(filePath, 'utf-8'); + return data.split('\n').map(Number); +} + +// Function to calculate and find the result from the secret numbers +function calculateMaxChange(inputNumbers) { + const result = {}; + + inputNumbers.forEach((n) => { + const ss = [...hsh(n)].map(s => s % 10); + const diffs = []; + + // Calculate the differences between adjacent elements + for (let i = 1; i < ss.length; i++) { + diffs.push(ss[i] - ss[i - 1]); + } + + const changes = new Set(); + + // Check for unique 4-length slices of the differences + for (let i = 0; i < diffs.length - 4; i++) { + const change = JSON.stringify(diffs.slice(i, i + 4)); + if (!changes.has(change)) { + changes.add(change); + const sum = ss[i + 4]; + result[change] = (result[change] || 0) + sum; + } + } + }); + + return Math.max(...Object.values(result)); +} + +// Main execution +function main() { + const inputNumbers = readInput('input.txt'); + const result = calculateMaxChange(inputNumbers); + console.log(result); +} + +main();",node:14 +2024,22,2,"--- Day 22: Monkey Market --- + +As you're all teleported deep into the jungle, a monkey steals The Historians' device! You'll need to get it back while The Historians are looking for the Chief. + +The monkey that stole the device seems willing to trade it, but only in exchange for an absurd number of bananas. Your only option is to buy bananas on the Monkey Exchange Market. + +You aren't sure how the Monkey Exchange Market works, but one of The Historians senses trouble and comes over to help. Apparently, they've been studying these monkeys for a while and have deciphered their secrets. + +Today, the Market is full of monkeys buying good hiding spots. Fortunately, because of the time you recently spent in this jungle, you know lots of good hiding spots you can sell! If you sell enough hiding spots, you should be able to get enough bananas to buy the device back. + +On the Market, the buyers seem to use random prices, but their prices are actually only pseudorandom! If you know the secret of how they pick their prices, you can wait for the perfect time to sell. + +The part about secrets is literal, the Historian explains. Each buyer produces a pseudorandom sequence of secret numbers where each secret is derived from the previous. + +In particular, each buyer's secret number evolves into the next secret number in the sequence via the following process: + +Calculate the result of multiplying the secret number by 64. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of dividing the secret number by 32. Round the result down to the nearest integer. Then, mix this result into the secret number. Finally, prune the secret number. +Calculate the result of multiplying the secret number by 2048. Then, mix this result into the secret number. Finally, prune the secret number. +Each step of the above process involves mixing and pruning: + +To mix a value into the secret number, calculate the bitwise XOR of the given value and the secret number. Then, the secret number becomes the result of that operation. (If the secret number is 42 and you were to mix 15 into the secret number, the secret number would become 37.) +To prune the secret number, calculate the value of the secret number modulo 16777216. Then, the secret number becomes the result of that operation. (If the secret number is 100000000 and you were to prune the secret number, the secret number would become 16113920.) +After this process completes, the buyer is left with the next secret number in the sequence. The buyer can repeat this process as many times as necessary to produce more secret numbers. + +So, if a buyer had a secret number of 123, that buyer's next ten secret numbers would be: + +15887950 +16495136 +527345 +704524 +1553684 +12683156 +11100544 +12249484 +7753432 +5908254 +Each buyer uses their own secret number when choosing their price, so it's important to be able to predict the sequence of secret numbers for each buyer. Fortunately, the Historian's research has uncovered the initial secret number of each buyer (your puzzle input). For example: + +1 +10 +100 +2024 +This list describes the initial secret number of four different secret-hiding-spot-buyers on the Monkey Exchange Market. If you can simulate secret numbers from each buyer, you'll be able to predict all of their future prices. + +In a single day, buyers each have time to generate 2000 new secret numbers. In this example, for each buyer, their initial secret number and the 2000th new secret number they would generate are: + +1: 8685429 +10: 4700978 +100: 15273692 +2024: 8667524 +Adding up the 2000th new secret number for each buyer produces 37327623. + +For each buyer, simulate the creation of 2000 new secret numbers. What is the sum of the 2000th secret number generated by each buyer? + +Your puzzle answer was 15335183969. + +--- Part Two --- + +Of course, the secret numbers aren't the prices each buyer is offering! That would be ridiculous. Instead, the prices the buyer offers are just the ones digit of each of their secret numbers. + +So, if a buyer starts with a secret number of 123, that buyer's first ten prices would be: + +3 (from 123) +0 (from 15887950) +6 (from 16495136) +5 (etc.) +4 +4 +6 +4 +4 +2 +This price is the number of bananas that buyer is offering in exchange for your information about a new hiding spot. However, you still don't speak monkey, so you can't negotiate with the buyers directly. The Historian speaks a little, but not enough to negotiate; instead, he can ask another monkey to negotiate on your behalf. + +Unfortunately, the monkey only knows how to decide when to sell by looking at the changes in price. Specifically, the monkey will only look for a specific sequence of four consecutive changes in price, then immediately sell when it sees that sequence. + +So, if a buyer starts with a secret number of 123, that buyer's first ten secret numbers, prices, and the associated changes would be: + + 123: 3 +15887950: 0 (-3) +16495136: 6 (6) + 527345: 5 (-1) + 704524: 4 (-1) + 1553684: 4 (0) +12683156: 6 (2) +11100544: 4 (-2) +12249484: 4 (0) + 7753432: 2 (-2) +Note that the first price has no associated change because there was no previous price to compare it with. + +In this short example, within just these first few prices, the highest price will be 6, so it would be nice to give the monkey instructions that would make it sell at that time. The first 6 occurs after only two changes, so there's no way to instruct the monkey to sell then, but the second 6 occurs after the changes -1,-1,0,2. So, if you gave the monkey that sequence of changes, it would wait until the first time it sees that sequence and then immediately sell your hiding spot information at the current price, winning you 6 bananas. + +Each buyer only wants to buy one hiding spot, so after the hiding spot is sold, the monkey will move on to the next buyer. If the monkey never hears that sequence of price changes from a buyer, the monkey will never sell, and will instead just move on to the next buyer. + +Worse, you can only give the monkey a single sequence of four price changes to look for. You can't change the sequence between buyers. + +You're going to need as many bananas as possible, so you'll need to determine which sequence of four price changes will cause the monkey to get you the most bananas overall. Each buyer is going to generate 2000 secret numbers after their initial secret number, so, for each buyer, you'll have 2000 price changes in which your sequence can occur. + +Suppose the initial secret number of each buyer is: + +1 +2 +3 +2024 +There are many sequences of four price changes you could tell the monkey, but for these four buyers, the sequence that will get you the most bananas is -2,1,-1,3. Using that sequence, the monkey will make the following sales: + +For the buyer with an initial secret number of 1, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 2, changes -2,1,-1,3 first occur when the price is 7. +For the buyer with initial secret 3, the change sequence -2,1,-1,3 does not occur in the first 2000 changes. +For the buyer starting with 2024, changes -2,1,-1,3 first occur when the price is 9. +So, by asking the monkey to sell the first time each buyer's prices go down 2, then up 1, then down 1, then up 3, you would get 23 (7 + 7 + 9) bananas! + +Figure out the best sequence to tell the monkey so that by looking for that same sequence of changes in every buyer's future prices, you get the most bananas in total. What is the most bananas you can get?",1696,"""use strict"" + +const input = Deno.readTextFileSync(""day22-input.txt"").trim() + +const allNumbers = [ ] // BigInts + +const SIZE = 19 * 19 * 19 * 19 // four changes of 19 possibilities each (from -9 to +9) + +const market = [ ] + +const control = [ ] + + +function main() { + + processInput() + + for (let n = 0; n < SIZE; n++) { + + market.push(0) // total bananas for that four change sequence + + control.push(-1) + } + + processBuyers() + + let best = 0 + + for (const bananas of market) { if (bananas > best) { best = bananas } } + + console.log(""the answer is"", best) +} + +function processInput() { + + const rawLines = input.split(""\n"") + + for (const rawLine of rawLines) { + + const number = BigInt(rawLine.trim()) + + allNumbers.push(number) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function processBuyers() { + + let buyer = -1 + + for (const secret of allNumbers) { + + buyer += 1 + + processBuyer(buyer, secret) + } +} + +function processBuyer(buyer, secret) { + + let lastPrice = parseInt(secret % BigInt(10)) + + const changes = [ ] // last four changes only + + for (let n = 0; n < 2000; n++) { + + secret = processSecretNumberOnce(secret) + + const price = parseInt(secret % BigInt(10)) + + const change = price - lastPrice + + lastPrice = price + + if (changes.length < 4) { changes.push(change); continue } + + changes[0] = changes[1] + changes[1] = changes[2] + changes[2] = changes[3] + changes[3] = change + + const index = getIndex(changes[0], changes[1], changes[2], changes[3]) + + if (control[index] == buyer) { continue } // only the first occurrence matters + + control[index] = buyer + + market[index] += price + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function getIndex(a, b, c, d) { + + return (19 * 19 * 19 * (a + 9)) + (19 * 19 * (b + 9)) + (19 * (c + 9)) + (d + 9) +} + +/////////////////////////////////////////////////////////////////////////////// + +function processSecretNumberOnce(secret) { // expecting BigInt + + const a = secret * BigInt(64) + const b = a ^ secret + const step1 = b % BigInt(16777216) + + const c = step1 / BigInt(32) // BigInt automatically rounds down + const d = c ^ step1 + const step2 = d % BigInt(16777216) + + const e = step2 * BigInt(2048) + const f = e ^ step2 + const step3 = f % BigInt(16777216) + + return step3 +} + +/////////////////////////////////////////////////////////////////////////////// + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 340ms",node:14 +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"const fs = require('fs'); + +function main() { + const input = fs.readFileSync(""input.txt"", 'utf-8').trim(); + const lines = input.split(""\n""); + + const adj = {}; + lines.forEach(line => { + const [a, b] = line.split(""-""); + if (!adj[a]) adj[a] = []; + if (!adj[b]) adj[b] = []; + adj[a].push(b); + adj[b].push(a); + }); + + const triangles = new Set(); + for (const a in adj) { + const neighborsA = adj[a]; + neighborsA.forEach(i => { + neighborsA.forEach(j => { + if (adj[i].includes(j)) { + triangles.add(JSON.stringify([a, i, j].sort())); + } + }); + }); + } + + let ans = 0; + triangles.forEach(triangleStr => { + const [a, b, c] = JSON.parse(triangleStr); + if ([a, b, c].some(node => node.startsWith(""t""))) { + ans += 1; + } + }); + + console.log(ans); +} + +main();",node:14 +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"const fs = require('fs'); + +function readFile() { + const fileName = ""input.txt""; + const mapping = {}; + + const lines = fs.readFileSync(fileName, 'utf-8').trim().split(""\n""); + const tuples = lines.map(line => line.split(""-"")); + + // Add reverse order as well + tuples.forEach(tuple => { + mapping[tuple[0]] = mapping[tuple[0]] || []; + mapping[tuple[0]].push(tuple[1]); + + mapping[tuple[1]] = mapping[tuple[1]] || []; + mapping[tuple[1]].push(tuple[0]); + }); + + return mapping; +} + +function makeMappingPart1(mapping, computer, depth, lanParty, lanParties) { + // We have reached 3 computers, make sure to close the loop + if (depth === 0) { + if (lanParty[0] === lanParty[lanParty.length - 1] && lanParty.some(computer => computer.startsWith(""t""))) { + lanParties.add(JSON.stringify(lanParty.slice(0, 3).sort())); + } + return; + } + + // Check all computers that are connected to the current one + mapping[computer].forEach(val => { + lanParty.push(val); + makeMappingPart1(mapping, val, depth - 1, lanParty, lanParties); + lanParty.pop(); + }); +} + +function part1(mapping) { + const lanParties = new Set(); + // Find all LAN parties with exactly 3 computers + for (const computer in mapping) { + makeMappingPart1(mapping, computer, 3, [computer], lanParties); + } + + console.log(lanParties.size); +} + +function main() { + const mapping = readFile(); + + console.log(""Answer to part 1:""); + part1(mapping); +} + +main();",node:14 +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"const fs = require('fs'); + +// Read the input file and split into lines +const lines = fs.readFileSync('input.txt', 'utf-8').split('\n'); + +// Initialize connections object using Map to mimic defaultdict +const connections = new Map(); +const pairs = lines.map(line => line.split('-')); + +// Create connections between nodes +pairs.forEach(pair => { + if (!connections.has(pair[0])) connections.set(pair[0], new Set()); + if (!connections.has(pair[1])) connections.set(pair[1], new Set()); + connections.get(pair[0]).add(pair[1]); + connections.get(pair[1]).add(pair[0]); +}); + +// Find trios by checking intersections of connections +const trios = new Set(); +pairs.forEach(pair => { + const intersection = [...connections.get(pair[0])].filter(val => connections.get(pair[1]).has(val)); + intersection.forEach(val => { + const trio = [pair[0], pair[1], val].sort(); + trios.add(JSON.stringify(trio)); + }); +}); + +// Filter trios with at least one value starting with 't' +const triosWithT = [...trios].filter(trio => { + const trioArray = JSON.parse(trio); + return trioArray.some(v => v.startsWith('t')); +}); + +console.log(triosWithT.length);",node:14 +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"// solution for https://adventofcode.com/2024/day/23 part 1 + +""use strict"" + +const input = Deno.readTextFileSync(""day23-input.txt"").trim() + +const allConnections = { } + +const allTargets = { } + +const alreadyDone = { } + +var targetCount = 0 + + +function main() { + + processInput() + + fillAllTargets() + + console.log(""the answer is"", targetCount) +} + +function processInput() { + + const rawLines = input.split(""\n"") + + for (const rawLine of rawLines) { + + const pair = rawLine.trim().split(""-"") + + const a = pair.shift() + const b = pair.shift() + + if (allConnections[a] == undefined) { allConnections[a] = [ ] } + if (allConnections[b] == undefined) { allConnections[b] = [ ] } + + allConnections[a].push(b) + allConnections[b].push(a) + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function fillAllTargets() { + + const allComputers = Object.keys(allConnections) + + for (const computer of allComputers) { fillTargetsFor(computer) } +} + +function fillTargetsFor(computer) { + + alreadyDone[computer] = true + + const friends = allConnections[computer] + + const off = friends.length + + for (let a = 0; a < off - 1; a++) { + + for (let b = a + 1; b < off; b++) { + + const friendA = friends[a] + const friendB = friends[b] + + if (computer[0] != ""t"" && friendA[0] != ""t"" && friendB[0] != ""t"") { continue } + + if (alreadyDone[friendA]) { continue } + if (alreadyDone[friendB]) { continue } + + if (! allConnections[friendA].includes(friendB)) { continue } + + const id = [ computer, friendA, friendB ].sort().join(""~"") + + if (allTargets[id]) { continue } + + allTargets[id] = true + + targetCount += 1 + } + } +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 9ms",node:14 +2024,23,1,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t?",1194,"const fs = require('fs'); + +function buildGraph(input) { + const graph = new Map(); + + input.split('\n').forEach(line => { + const [a, b] = line.split('-'); + if (!graph.has(a)) graph.set(a, new Set()); + if (!graph.has(b)) graph.set(b, new Set()); + graph.get(a).add(b); + graph.get(b).add(a); + }); + + return graph; +} + +function findConnectedTriples(graph) { + const triples = new Set(); + + // For each node + for (const [node1, neighbors1] of graph) { + // For each neighbor of first node + for (const node2 of neighbors1) { + // For each neighbor of second node + for (const node3 of graph.get(node2)) { + // Check if third node connects back to first + if (node3 !== node1 && graph.get(node3).has(node1)) { + // Sort nodes to ensure unique combinations + const triple = [node1, node2, node3].sort().join(','); + triples.add(triple); + } + } + } + } + + return Array.from(triples); +} + +function countTriplesWithT(triples) { + return triples.filter(triple => + triple.split(',').some(node => node.startsWith('t')) + ).length; +} + +function solve(input) { + const graph = buildGraph(input); + const triples = findConnectedTriples(graph); + return countTriplesWithT(triples); +} + +const input = fs.readFileSync('input.txt', 'utf8').trim(); +console.log(solve(input));",node:14 +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +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,qc,rn,so,tm,wf,yl,ys,ze,zr","const fs = require('fs'); + +// Parse input file +function parse() { + const lines = fs.readFileSync(""input.txt"", ""utf8"").split(""\n""); + return lines.map(line => { + const [a, b] = line.trim().split(""-""); + return [a, b]; + }); +} + +// Generate graph (adjacency list) +function generateGraph(connections) { + const nodes = {}; + connections.forEach(connection => { + const [a, b] = connection; + if (!nodes[a]) nodes[a] = new Set(); + if (!nodes[b]) nodes[b] = new Set(); + nodes[a].add(b); + nodes[b].add(a); + }); + return nodes; +} + +// Part 1: Find a three-length loop with at least one containing 't' +function part1() { + const connections = parse(); + const graph = generateGraph(connections); + + const found = new Set(); + for (const node in graph) { + const neighbors = graph[node]; + neighbors.forEach(neighbor => { + graph[neighbor].forEach(neighborsNeighbor => { + if (graph[neighborsNeighbor].has(node)) { + if (node.startsWith(""t"") || neighbor.startsWith(""t"") || neighborsNeighbor.startsWith(""t"")) { + const sortedNodes = [node, neighbor, neighborsNeighbor].sort(); + found.add(sortedNodes.join(""-"")); + } + } + }); + }); + } + + console.log(found.size); +} + +// Check if a node's neighbors are all in the subgraph +function neighborsAll(node, graph, subgraph) { + for (const n of subgraph) { + if (!graph[n].has(node)) { + return false; + } + } + return true; +} + +// Part 2: Find the biggest subgraph where all nodes are connected to each other +function part2() { + const connections = parse(); + const graph = generateGraph(connections); + + let biggestSubgraph = new Set(); + for (const node in graph) { + let result = new Set(); + result.add(node); + graph[node].forEach(neighbor => { + if (neighborsAll(neighbor, graph, result)) { + result.add(neighbor); + } + }); + + if (result.size > biggestSubgraph.size) { + biggestSubgraph = result; + } + } + + const inOrder = Array.from(biggestSubgraph).sort(); + console.log(inOrder.join("","")); +} + +// Run Part 2 +part2();",node:14 +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +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,qc,rn,so,tm,wf,yl,ys,ze,zr","const fs = require('fs'); + +function buildGraph(input) { + const graph = new Map(); + + input.split('\n').forEach(line => { + const [a, b] = line.split('-'); + if (!graph.has(a)) graph.set(a, new Set()); + if (!graph.has(b)) graph.set(b, new Set()); + graph.get(a).add(b); + graph.get(b).add(a); + }); + + return graph; +} + +function isClique(graph, nodes) { + // Check if every node connects to every other node + for (let i = 0; i < nodes.length; i++) { + const neighbors = graph.get(nodes[i]); + for (let j = 0; j < nodes.length; j++) { + if (i !== j && !neighbors.has(nodes[j])) { + return false; + } + } + } + return true; +} + +function findMaximalClique(graph) { + let maxClique = []; + const nodes = Array.from(graph.keys()); + + // Helper function to extend current clique + function extend(current, candidates) { + if (candidates.length === 0) { + if (current.length > maxClique.length) { + maxClique = [...current]; + } + return; + } + + for (let i = 0; i < candidates.length; i++) { + const candidate = candidates[i]; + const newCurrent = [...current, candidate]; + + // Only continue if this is still a valid clique + if (isClique(graph, newCurrent)) { + // Filter candidates to those that are connected to all current nodes + const newCandidates = candidates.slice(i + 1).filter(node => + newCurrent.every(currentNode => + graph.get(currentNode).has(node) + ) + ); + extend(newCurrent, newCandidates); + } + } + } + + extend([], nodes); + return maxClique; +} + +function solve(input) { + const graph = buildGraph(input); + const maxClique = findMaximalClique(graph); + return maxClique.sort().join(','); +} + +const input = fs.readFileSync('input.txt', 'utf8').trim(); +console.log(solve(input));",node:14 +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +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,qc,rn,so,tm,wf,yl,ys,ze,zr","// solution for https://adventofcode.com/2024/day/23 part 2 + +""use strict"" + +const input = Deno.readTextFileSync(""day23-input.txt"").trim() + +const allConnections = { } + +const allNetworks = [ ] + +var greatestNetworkLength = 0 + +var bestNetwork = [ ] + + +function main() { + + processInput() + + fillAllNetworks() + + search() + + console.log(""the answer is"", bestNetwork.sort().join("","")) +} + +/////////////////////////////////////////////////////////////////////////////// + +function processInput() { + + const rawLines = input.split(""\n"") + + for (const rawLine of rawLines) { + + const pair = rawLine.trim().split(""-"") + + const a = pair.shift() + const b = pair.shift() + + if (allConnections[a] == undefined) { allConnections[a] = [ ] } + if (allConnections[b] == undefined) { allConnections[b] = [ ] } + + allConnections[a].push(b) + allConnections[b].push(a) + } +} + +function fillAllNetworks() { + + const allComputers = Object.keys(allConnections) + + for (const computer of allComputers) { + + const network = allConnections[computer].slice() + + network.unshift(computer) + + allNetworks.push(network) + + if (network.length > greatestNetworkLength) { greatestNetworkLength = network.length } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function search() { + + for (const network of allNetworks) { // searches without removing any member + + if (! allMembersAreFriends(network)) { continue } + + if (network.length > bestNetwork.length) { bestNetwork = network } + + if (bestNetwork.length == greatestNetworkLength) { return } + } + + while (true) { + + searchRemovingTheWorstMember() + + if (bestNetwork.length != 0) { return } + } +} + +function searchRemovingTheWorstMember() { + + greatestNetworkLength -= 1 + + for (const network of allNetworks) { + + removeTheWorstMember(network) + + if (! allMembersAreFriends(network)) { continue } + + if (network.length > bestNetwork.length) { bestNetwork = network } + + if (bestNetwork.length == greatestNetworkLength) { return } + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function removeTheWorstMember(network) { // expects network having at least one bad member + + const unfriendship = [ ] + + for (let n = 0; n < network.length; n++) { unfriendship.push(0) } + + + let worstIndex = 0 + let worstValue = -1 + + const off = network.length + + for (let a = 0; a < off - 1; a++) { + + const computerA = network[a] + + const connectionsA = allConnections[computerA] + + for (let b = a + 1; b < off; b++) { + + const computerB = network[b] + + if (connectionsA.includes(computerB)) { continue } + + unfriendship[a] += 1 + unfriendship[b] += 1 + + if (unfriendship[a] > worstValue) { worstValue = unfriendship[a]; worstIndex = a } + if (unfriendship[b] > worstValue) { worstValue = unfriendship[b]; worstIndex = b } + } + } + + // if (worstIndex == -1) { return } // not needed + + network.splice(worstIndex, 1) +} + +/////////////////////////////////////////////////////////////////////////////// + +function allMembersAreFriends(network) { + + const off = network.length + + for (let a = 0; a < off - 1; a++) { + + const computerA = network[a] + + const connectionsA = allConnections[computerA] + + for (let b = a + 1; b < off; b++) { + + const computerB = network[b] + + if (! connectionsA.includes(computerB)) { return false } + } + } + + return true +} + +/////////////////////////////////////////////////////////////////////////////// + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 5ms",node:14 +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +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,qc,rn,so,tm,wf,yl,ys,ze,zr","const fs = require('fs'); + +// Read the input file +const inputText = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n""); + +const connections = {}; + +// Populate the connections map +inputText.forEach(connection => { + const [person1, person2] = connection.split(""-""); + if (!connections[person1]) connections[person1] = new Set(); + if (!connections[person2]) connections[person2] = new Set(); + connections[person1].add(person2); + connections[person2].add(person1); +}); + +let maxCliqueSize = 0; +let maxClique = new Set(); + +// bron-kerbosch algorithm +function bronKerbosch(R, P, X) { + if (P.size === 0 && X.size === 0 && R.size > maxCliqueSize) { + maxClique = new Set(R); + maxCliqueSize = R.size; + } + + // Create a copy of P to iterate over + P = new Set(P); + + P.forEach(person => { + bronKerbosch( + new Set([...R, person]), + intersection(P, connections[person]), + intersection(X, connections[person]) + ); + P.delete(person); + X.add(person); + }); +} + +// Helper function to find intersection of two sets +function intersection(set1, set2) { + const result = new Set(); + set1.forEach(value => { + if (set2.has(value)) { + result.add(value); + } + }); + return result; +} + +// Initialize P and X +const allPersons = Object.keys(connections); +bronKerbosch(new Set(), new Set(allPersons), new Set()); + +console.log(Array.from(maxClique).sort().join("",""));",node:14 +2024,23,2,"--- Day 23: LAN Party --- + +As The Historians wander around a secure area at Easter Bunny HQ, you come across posters for a LAN party scheduled for today! Maybe you can find it; you connect to a nearby datalink port and download a map of the local network (your puzzle input). + +The network map provides a list of every connection between two computers. For example: + +kh-tc +qp-kh +de-cg +ka-co +yn-aq +qp-ub +cg-tb +vc-aq +tb-ka +wh-tc +yn-cg +kh-ub +ta-co +de-co +tc-td +tb-wq +wh-td +ta-ka +td-qp +aq-cg +wq-ub +ub-vc +de-ta +wq-aq +wq-vc +wh-yn +ka-de +kh-ta +co-tc +wh-qp +tb-vc +td-yn +Each line of text in the network map represents a single connection; the line kh-tc represents a connection between the computer named kh and the computer named tc. Connections aren't directional; tc-kh would mean exactly the same thing. + +LAN parties typically involve multiplayer games, so maybe you can locate it by finding groups of connected computers. Start by looking for sets of three computers where each computer in the set is connected to the other two computers. + +In this example, there are 12 such sets of three inter-connected computers: + +aq,cg,yn +aq,vc,wq +co,de,ka +co,de,ta +co,ka,ta +de,ka,ta +kh,qp,ub +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +ub,vc,wq +If the Chief Historian is here, and he's at the LAN party, it would be best to know that right away. You're pretty sure his computer's name starts with t, so consider only sets of three computers where at least one computer's name starts with t. That narrows the list down to 7 sets of three inter-connected computers: + +co,de,ta +co,ka,ta +de,ka,ta +qp,td,wh +tb,vc,wq +tc,td,wh +td,wh,yn +Find all the sets of three inter-connected computers. How many contain at least one computer with a name that starts with t? + +Your puzzle answer was 1194. + +--- Part Two --- + +There are still way too many results to go through them all. You'll have to find the LAN party another way and go there yourself. + +Since it doesn't seem like any employees are around, you figure they must all be at the LAN party. If that's true, the LAN party will be the largest set of computers that are all connected to each other. That is, for each computer at the LAN party, that computer will have a connection to every other computer at the LAN party. + +In the above example, the largest set of computers that are all connected to each other is made up of co, de, ka, and ta. Each computer in this set has a connection to every other computer in the set: + +ka-co +ta-co +de-co +ta-ka +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,qc,rn,so,tm,wf,yl,ys,ze,zr","const fs = require('fs'); + +// Function to check if the nodes form a clique +function isClique(connections, nodes) { + for (let i = 0; i < nodes.length; i++) { + for (let j = i + 1; j < nodes.length; j++) { + if (!connections[nodes[i]].has(nodes[j])) { + return false; + } + } + } + return true; +} + +// Function to find the largest clique starting at a given node +function maxCliqueStartingAt(connections, node) { + const neighbors = Array.from(connections[node]); + for (let i = neighbors.length; i > 1; i--) { + const combinations = getCombinations(neighbors, i); + for (let group of combinations) { + if (isClique(connections, group)) { + return new Set([node, ...group]); + } + } + } + return new Set(); +} + +// Function to get combinations of a given size from an array +function getCombinations(arr, size) { + const result = []; + const helper = (current, start) => { + if (current.length === size) { + result.push(current); + return; + } + for (let i = start; i < arr.length; i++) { + helper([...current, arr[i]], i + 1); + } + }; + helper([], 0); + return result; +} + +// Read input file and process it +const fileContent = fs.readFileSync('input.txt', 'utf8').trim().split(""\n""); + +const connections = {}; +fileContent.forEach(line => { + const [a, b] = line.split(""-""); + if (!connections[a]) connections[a] = new Set(); + if (!connections[b]) connections[b] = new Set(); + connections[a].add(b); + connections[b].add(a); +}); + +// Find the largest clique +let cliques = []; +Object.keys(connections).forEach(node => { + const clique = maxCliqueStartingAt(connections, node); + if (clique.size > 0) { + cliques.push(clique); + } +}); + +// Get the largest clique +const maxClique = cliques.reduce((max, clique) => (clique.size > max.size ? clique : max), new Set()); + +// Print the largest clique sorted +console.log(Array.from(maxClique).sort().join("",""));",node:14 +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"const fs = require('fs'); + +// Helper function to parse the input file and initialize wire values +function initializeWires(inputText) { + const wires = {}; + inputText.forEach(line => { + const [wire, val] = line.split("": ""); + wires[wire] = parseInt(val, 10); + }); + return wires; +} + +// Helper function to evaluate gates and update wires +function evaluateGates(wires, outVals) { + let q = [...outVals]; + while (q.length > 0) { + const curr = q.shift(); + const [wiresIn, outWire] = curr.split("" -> ""); + const [left, op, right] = wiresIn.split("" ""); + + // Skip the gate if the required wires aren't available + if (!(left in wires) || !(right in wires)) { + q.push(curr); + continue; + } + + let result; + switch (op) { + case ""XOR"": + result = wires[left] ^ wires[right]; + break; + case ""OR"": + result = wires[left] | wires[right]; + break; + case ""AND"": + result = wires[left] & wires[right]; + break; + default: + throw new Error(`Unknown operation: ${op}`); + } + + wires[outWire] = result; + } +} + +// Helper function to categorize wires by type +function categorizeWires(wires) { + const xWires = [], yWires = [], zWires = []; + for (let wire in wires) { + if (wire.includes(""x"")) { + xWires.push(wire); + } else if (wire.includes(""y"")) { + yWires.push(wire); + } else if (wire.includes(""z"")) { + zWires.push(wire); + } + } + return { xWires, yWires, zWires }; +} + +// Helper function to convert wire values to binary and then decimal +function toDecimal(wires, wireList) { + const digits = wireList.map(w => wires[w].toString()); + return parseInt(digits.join(''), 2); +} + +// Main function +function main() { + // Read and parse the input file + const inputText = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n\n""); + const inVals = inputText[0].split(""\n""); + const outVals = inputText[1].split(""\n""); + + // Initialize wires from the input + let wires = initializeWires(inVals); + + // Evaluate the gates + evaluateGates(wires, outVals); + + // Categorize wires into x, y, and z categories + const { xWires, yWires, zWires } = categorizeWires(wires); + + // Sort the wires in reverse order + xWires.sort((a, b) => b.localeCompare(a)); + yWires.sort((a, b) => b.localeCompare(a)); + zWires.sort((a, b) => b.localeCompare(a)); + + // Convert wire values to decimal + const xDec = toDecimal(wires, xWires); + const yDec = toDecimal(wires, yWires); + const zDec = toDecimal(wires, zWires); + + // Print the result for part one + console.log(""Part One:"", zDec); +} + +// Run the main function +main();",node:14 +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"const fs = require('fs'); +const readline = require('readline'); + +// Read input file +const inputText = fs.readFileSync(""input.txt"", ""utf8"").trim().split(""\n\n""); +const inVals = inputText[0].split(""\n""); +const outVals = inputText[1].split(""\n""); + +let wires = {}; +inVals.forEach(line => { + const [wire, val] = line.split("": ""); + wires[wire] = parseInt(val, 10); +}); + +let q = [...outVals]; +while (q.length > 0) { + const curr = q.shift(); + const [wiresIn, outWire] = curr.split("" -> ""); + const [left, op, right] = wiresIn.split("" ""); + + if (!(left in wires) || !(right in wires)) { + q.push(curr); + continue; + } + + let result = -1; + if (op === ""XOR"") { + result = wires[left] ^ wires[right]; + } else if (op === ""OR"") { + result = wires[left] | wires[right]; + } else if (op === ""AND"") { + result = wires[left] & wires[right]; + } + + wires[outWire] = result; +} + +let xWires = [], yWires = [], zWires = []; +for (let wire in wires) { + if (wire.includes(""x"")) { + xWires.push(wire); + } else if (wire.includes(""y"")) { + yWires.push(wire); + } else if (wire.includes(""z"")) { + zWires.push(wire); + } +} + +xWires.sort((a, b) => b.localeCompare(a)); +yWires.sort((a, b) => b.localeCompare(a)); +zWires.sort((a, b) => b.localeCompare(a)); + +let xDigits = xWires.map(w => wires[w].toString()); +let yDigits = yWires.map(w => wires[w].toString()); +let zDigits = zWires.map(w => wires[w].toString()); + +let xDec = parseInt(xDigits.join(''), 2); +let yDec = parseInt(yDigits.join(''), 2); +let zDec = parseInt(zDigits.join(''), 2); + +let partOne = zDec; +console.log(""Part One:"", partOne);",node:14 +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"// solution for https://adventofcode.com/2024/day/24 part 1 + +""use strict"" + +const input = Deno.readTextFileSync(""day24-input.txt"").trim() + +const allWires = { } + +var gatesToRun = [ ] + + +function main() { + + processInput() + + runCircuit() + + console.log(""the answer is"", calcResult()) +} + +/////////////////////////////////////////////////////////////////////////////// + +function processInput() { + + const sections = input.split(""\n\n"") + + const rawGates = sections.pop().trim().split(""\n"") // doing gates first, some wires will be overriden + + for (const rawGate of rawGates) { + + const parts = rawGate.trim().split("" "") + + const wire1 = parts.shift() + const kind = parts.shift() + const wire2 = parts.shift() + parts.shift() // -> + const wire3 = parts.shift() + + gatesToRun.push(createGateObj(kind, wire1, wire2, wire3)) + + allWires[wire1] = -1 + allWires[wire2] = -1 + allWires[wire3] = -1 + } + + const rawWires = sections.pop().trim().split(""\n"") + + for (const rawWire of rawWires) { + + const parts = rawWire.split("": "") + + const wire = parts.shift() + + const value = parseInt(parts.shift()) + + allWires[wire] = value + } +} + +function createGateObj(kind, wire1, wire2, wire3) { + + return { + ""kind"": kind, + ""wire1"": wire1, + ""wire2"": wire2, + ""wire3"": wire3 + } +} + +/////////////////////////////////////////////////////////////////////////////// + +function runCircuit() { + + while (gatesToRun.length != 0) { + + gatesToRun = runCircuitOnce() + } +} + +function runCircuitOnce() { + + const remainingGatesToRun = [ ] + + for (const gate of gatesToRun) { + + const value1 = allWires[gate.wire1] + + if (value1 == -1) { remainingGatesToRun.push(gate); continue } + + const value2 = allWires[gate.wire2] + + if (value2 == -1) { remainingGatesToRun.push(gate); continue } + + const sum = value1 + value2 + + let output = 0 + + if (gate.kind == ""AND"") { if (sum == 2) { output = 1 } } + + else if (gate.kind == ""OR"") { if (sum != 0) { output = 1 } } + + else if (gate.kind == ""XOR"") { if (sum == 1) { output = 1 } } + + allWires[gate.wire3] = output + } + + return remainingGatesToRun +} + +/////////////////////////////////////////////////////////////////////////////// + +function calcResult() { + + let binary = """" + + let reversedPos = -1 + + while (true) { + + reversedPos += 1 + + const prefix = (reversedPos < 10) ? ""0"" : """" + + const wire = ""z"" + prefix + reversedPos + + const value = allWires[wire] + + if (value == undefined) { break } + + binary = value + binary + } + + return parseInt(binary, 2) +} + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 2ms",node:14 +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"const fs = require('fs'); + +class Wire { + constructor(name, wireVal) { + this.name = name; + this.wireVal = wireVal; + } +} + +class Gate { + constructor(logic, input1, input2) { + this.logic = logic; + this.input1 = input1; + this.input2 = input2; + } + + getOutput(wireDict) { + if (this.logic === ""AND"") { + return (wireDict[this.input1].wireVal === ""1"" && wireDict[this.input2].wireVal === ""1"") ? ""1"" : ""0""; + } else if (this.logic === ""OR"") { + return (wireDict[this.input1].wireVal === ""1"" || wireDict[this.input2].wireVal === ""1"") ? ""1"" : ""0""; + } else if (this.logic === ""XOR"") { + return (wireDict[this.input1].wireVal !== wireDict[this.input2].wireVal) ? ""1"" : ""0""; + } + } +} + +const inputText = fs.readFileSync(""input.txt"", ""utf8"").split(""\n""); + +let wires = {}; +let gates = {}; + +inputText.forEach(line => { + line = line.trim(); + if (line.includes("":"")) { + const [name, value] = line.split("": ""); + wires[name] = new Wire(name, value); + } else if (line.includes(""->"")) { + const parts = line.split("" ""); + gates[parts[4]] = new Gate(parts[1], parts[0], parts[2]); + } +}); + +while (Object.keys(gates).some(gate => !(gate in wires))) { + Object.keys(gates).forEach(gate => { + const currentGate = gates[gate]; + if (wires[currentGate.input1] && wires[currentGate.input2]) { + const outputVal = currentGate.getOutput(wires); + wires[gate] = new Wire(gate, outputVal); + } + }); +} + +const zWires = Object.keys(wires) + .filter(wire => wires[wire].name.startsWith(""z"")) + .sort(); + +let zBits = zWires.reverse().map(z => wires[z].wireVal).join(''); + +console.log('Decimal number output on the wires starting with ""z"":', parseInt(zBits, 2));",node:14 +2024,24,1,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z?",52956035802096,"const fs = require('fs'); + +// Read input from file +const inputText = fs.readFileSync('input.txt', 'utf8').split('\n'); + +// Initialize wires and gates +let wires = {}; +let gates = []; + +let initial = true; +inputText.forEach(line => { + if (line === '') { + initial = false; + return; + } + + if (initial) { + const [wire, value] = line.split(' '); + wires[wire.slice(0, -1)] = parseInt(value); + } else { + const gate = line.trim().split(' '); + gates.push([gate[0], gate[1], gate[2], gate[4], false]); + } +}); + +// Initialize wires for gates +gates.forEach(gate => { + if (!(gate[0] in wires)) { + wires[gate[0]] = -1; + } + if (!(gate[2] in wires)) { + wires[gate[2]] = -1; + } +}); + +// Process gates until all are done +let allDone = false; +while (!allDone) { + console.log('*', ''); + allDone = true; + + gates.forEach(gate => { + if (wires[gate[0]] !== -1 && wires[gate[2]] !== -1 && !gate[4]) { + if (gate[1] === 'AND') { + wires[gate[3]] = (wires[gate[0]] + wires[gate[2]] === 2) ? 1 : 0; + } else if (gate[1] === 'OR') { + wires[gate[3]] = (wires[gate[0]] + wires[gate[2]] >= 1) ? 1 : 0; + } else { + wires[gate[3]] = (wires[gate[0]] !== wires[gate[2]]) ? 1 : 0; + } + gate[4] = true; + console.log('.', ''); + } else if (!gate[4]) { + allDone = false; + } + }); +} + +let output = {}; +for (const [key, val] of Object.entries(wires)) { + if (key[0] === 'z') { + output[key] = val; + } +} + +let sortedOutput = Object.entries(output).sort((a, b) => { + return a[0].localeCompare(b[0]); +}); + +let dec = 0; +let power = 0; +sortedOutput.forEach(([key, val]) => { + console.log(key, val); + dec += val * Math.pow(2, power); + power += 1; +}); + +console.log(dec);",node:14 +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +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,tqr,vmv,z07,z20,z28","const fs = require('fs'); + +function parseInput(file) { + const data = fs.readFileSync(file, 'utf8').trim().split('\n'); + const wireValues = {}; + const gates = []; + + data.forEach(line => { + if (line.includes('->')) { + gates.push(line); + } else { + const [wire, value] = line.split(': '); + wireValues[wire] = parseInt(value, 10); + } + }); + return { wireValues, gates }; +} + +function collectOutputs(wireValues, prefix) { + return Object.keys(wireValues) + .filter(key => key.startsWith(prefix)) + .sort() + .map(key => wireValues[key]); +} + +function isInput(operand) { + return operand.startsWith('x') || operand.startsWith('y'); +} + +function buildUsageMap(gates) { + const usageMap = new Map(); + gates.forEach(gate => { + const [left, op, right, _, result] = gate.split(' '); + [left, right].forEach(key => { + if (!usageMap.has(key)) { + usageMap.set(key, []); + } + usageMap.get(key).push(gate); + }); + }); + return usageMap; +} + +function validateXOR(left, right, result, usageMap) { + if (isInput(left)) { + if (!isInput(right) || (result.startsWith('z') && result !== 'z00')) { + return true; + } + const usageOps = usageMap.get(result)?.map(op => op.split(' ')[1]) || []; + if (result !== 'z00' && usageOps.sort().join(',') !== 'AND,XOR') { + return true; + } + } else if (!result.startsWith('z')) { + return true; + } + return false; +} + +function validateAND(left, right, result, usageMap) { + if (isInput(left) && !isInput(right)) { + return true; + } + const usageOps = usageMap.get(result)?.map(op => op.split(' ')[1]) || []; + return usageOps.join(',') !== 'OR'; +} + +function validateOR(left, right, result, usageMap) { + if (isInput(left) || isInput(right)) { + return true; + } + const usageOps = usageMap.get(result)?.map(op => op.split(' ')[1]) || []; + return usageOps.sort().join(',') !== 'AND,XOR'; +} + +function findSwappedWires(wireValues, gates) { + const usageMap = buildUsageMap(gates); + const swappedWires = new Set(); + + gates.forEach(gate => { + const [left, op, right, _, result] = gate.split(' '); + if (result === 'z45' || left === 'x00') return; + + if ((op === 'XOR' && validateXOR(left, right, result, usageMap)) || + (op === 'AND' && validateAND(left, right, result, usageMap)) || + (op === 'OR' && validateOR(left, right, result, usageMap))) { + swappedWires.add(result); + } + }); + + return [...swappedWires].sort(); +} + +const { wireValues, gates } = parseInput('input.txt'); +console.log(findSwappedWires(wireValues, gates).join(','));",node:14 +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +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,tqr,vmv,z07,z20,z28","import { readFileSync } from ""fs""; + +export default function day24() { + let input = readFileSync('input.txt', 'utf-8'); + + let [inputsS, ops] = input.split(/(?:\r?\n){2}/) + + let adjList = {}; + + for(let line of ops.split(/\r?\n/)) { + let [v, output] = line.split(' -> '); + + let [_, v0, op, v1] = v.match(/(\w+) (\w+) (\w+)/); + + let operation = [v0, op, v1]; + + adjList[output] = operation; + } + + let [definitelyBroken, maybeBrokenMap] = getBreakages(false); + let maybeBrokenArr = [...maybeBrokenMap.keys()]; + let definitelyBrokenIndexes = [...definitelyBroken].map(x => maybeBrokenArr.findIndex(z => z === x)); + + // console.log(...maybeBrokenMap.entries()) + console.log(definitelyBroken) + console.log(maybeBrokenMap) + + + let result = dfs(maybeBrokenArr, new Set()); + return result.sort().join(','); + + function dfs(maybeBroken, used) { + if(used.size === 8) { + for(let idx of definitelyBrokenIndexes) { + if(!used.has(idx)) { + return false; + } + } + + let [_, maybeBroken2] = getBreakages(true); + if(!maybeBroken2.size) { + return [...used].map(x => maybeBroken[x]); + } + return false; + } + for(let i = 0; i < maybeBroken.length; ++i) { + if(!definitelyBrokenIndexes.includes(i) && used.size < definitelyBrokenIndexes.length) { continue; } + + if(used.has(i)) { continue; } + used.add(i); + for(let j = i+1; j < maybeBroken.length; ++j) { + if(used.has(j)) { continue; } + used.add(j); + + + let v1 = maybeBroken[i]; + let v2 = maybeBroken[j]; + [adjList[v1], adjList[v2]] = [adjList[v2], adjList[v1]]; + + let ret = dfs(maybeBroken, used); + if(ret) { + return ret; + } + + [adjList[v1], adjList[v2]] = [adjList[v2], adjList[v1]]; + + used.delete(j); + } + used.delete(i); + } + } + + function getBreakages(bailEarly) { + let definitelyBroken = new Set(); + let maybeBrokenMap = new Map(); + function maybeBroken(...nodes) { + if(nodes.length < 2) { + definitelyBroken.add(nodes[0]); + } + for(let node of nodes) { + if(node) { + maybeBrokenMap.set(node, (maybeBrokenMap.get(node)??0)+1); + } + } + + return false; + } + for(let i = 0; i < 45; ++i) { + if(maybeBrokenMap.size && bailEarly) { return [definitelyBroken, maybeBrokenMap]; } + + let v = `z${i.toString().padStart(2, '0')}`; + + derive(v, i) + } + + return [definitelyBroken, maybeBrokenMap]; + + + + + function derive(v0, num) { + //expected: XOR(XOR(n), NEXT) + if(num < 1) { + if(!isXorFor(v0, num)) { + return maybeBroken(v0); + } + return true; + } + + let next = adjList[v0]; + if(next[1] !== 'XOR') { + // console.log(`broke -1 -->${v0}<--:..... (${i})`); + return maybeBroken(v0); + } + + let [v1, op, v2] = next; + + if(!adjList[v1] || !adjList[v2]) { + return maybeBroken(v0); + } + if(adjList[v2][1] === 'XOR') { + [v1, v2] = [v2, v1]; + } + if(adjList[v1][1] !== 'XOR') { + return maybeBroken(v0, v1, v2);//TODO not sure which?! + } + + if(!isXorFor(v1, num)) { + return maybeBroken(v0, v1, v2); + } + + //XOR OK... NOW FOR CARRY + return deriveCarry(v2, num-1); + } + function deriveCarry(v0, num) { + let [v1, op, v2] = adjList[v0]; + + if(num === 0) { + if(isAndFor(v0, num)) { + return true; + } + return maybeBroken(v0); + } + if(op !== 'OR') { + return maybeBroken(v0); + } + + if(isAndFor(v2, num)) { + [v2, v1] = [v1, v2]; + } + if(!isAndFor(v1, num)) { + return maybeBroken(v0, v1, v2); + } + + return deriveCarry2(v2, num); + } + function isAndFor(v0, num) { + if(!adjList[v0]) { + return maybeBroken(v0); + } + let [v1, op, v2] = adjList[v0]; + if(op !== 'AND' || !isForNum(v0, num)) { + return false; + } + + return true; + } + function isXorFor(v0, num) { + if(!adjList[v0]) { + return maybeBroken(v0); + } + let [v1, op, v2] = adjList[v0]; + if(op !== 'XOR' || !isForNum(v0, num)) { + return false; + } + + return true; + } + function isForNum(v0, num) { + let [v1, op, v2] = adjList[v0]; + + let digit1 = String.fromCharCode((Math.floor(num/10) % 10) + '0'.charCodeAt(0)); + let digit2 = String.fromCharCode((num % 10) + '0'.charCodeAt(0)); + return !(v1[1] !== digit1 || v1[2] !== digit2 || v2[1] !== digit1 || v2[2] !== digit2); + } + function deriveCarry2(v0, num) { + let [v1, op, v2] = adjList[v0]; + if(op !== 'AND') { + return maybeBroken(v0); + } + + if(isXorFor(v2, num)) { + [v1, v2] = [v2, v1]; + } + if(!isXorFor(v1, num)) { + return maybeBroken(v0, v1, v2); + } + return deriveCarry(v2, num-1) + } + } + + +} + +console.time() +console.log(day24()); +console.timeEnd()",node:14 +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +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,tqr,vmv,z07,z20,z28","const fs = require('fs'); + +function getExprForOutput(output) { + return outputToExpr[swaps[output] || output]; +} + +function getOutputForExpr(expr) { + const output = exprToOutput[expr]; + return swaps[output] || output; +} + +function swap(outA, outB) { + console.log(`SWAP: ${outA} for ${outB}`); + swaps[outA] = outB; + swaps[outB] = outA; +} + +function findMatchingExpr(output, op) { + const matching = Object.keys(exprToOutput).filter(expr => { + const [left, right, operator] = expr.split(','); + return operator === op && [left, right].includes(output); + }); + + if (matching.length === 0) { + return null; + } + if (matching.length > 1) { + throw new Error('More than one matching expression found'); + } + return matching[0].split(','); +} + +const outputToExpr = {}; +const exprToOutput = {}; +const swaps = {}; +const carries = []; + +let maxInputBitIndex = -1; + +const lines = fs.readFileSync('input.txt', 'utf8').split('\n'); + +lines.forEach(line => { + if (line.includes(""->"")) { + const [expr, wire] = line.split("" -> ""); + const [left, op, right] = expr.split("" ""); + + const sortedOperands = [left, right].sort(); + outputToExpr[wire] = [sortedOperands[0], sortedOperands[1], op]; + exprToOutput[`${sortedOperands[0]},${sortedOperands[1]},${op}`] = wire; + } + if (line.includes("":"")) { + maxInputBitIndex = Math.max(maxInputBitIndex, parseInt(line.split("":"")[0].slice(1))); + } +}); + +const numInputBits = maxInputBitIndex + 1; + +for (let i = 0; i < numInputBits; i++) { + const zOutput = `z${i.toString().padStart(2, '0')}`; + const inputXorExpr = [`x${i.toString().padStart(2, '0')}`, `y${i.toString().padStart(2, '0')}`, ""XOR""]; + const inputAndExpr = [`x${i.toString().padStart(2, '0')}`, `y${i.toString().padStart(2, '0')}`, ""AND""]; + + const inputXorOutput = getOutputForExpr(inputXorExpr); + const inputAndOutput = getOutputForExpr(inputAndExpr); + + if (i === 0) { + if (zOutput === inputXorOutput) { + carries.push(inputAndOutput); + continue; + } else { + throw new Error(""Error in first digits""); + } + } + + let resultExpr = findMatchingExpr(inputXorOutput, ""XOR""); + if (resultExpr === null) { + resultExpr = findMatchingExpr(carries[i - 1], ""XOR""); + const actualInputXorOutput = resultExpr[0] === carries[i - 1] ? resultExpr[1] : resultExpr[0]; + swap(actualInputXorOutput, inputXorOutput); + } else { + const carryInput = resultExpr[0] === inputXorOutput ? resultExpr[1] : resultExpr[0]; + if (carryInput !== carries[i - 1]) { + swap(carryInput, carries[i - 1]); + carries[i - 1] = carryInput; + } + } + + if (zOutput !== getOutputForExpr(resultExpr)) { + swap(zOutput, getOutputForExpr(resultExpr)); + } + + const intermediateCarryExpr = [getOutputForExpr(inputXorExpr), carries[i - 1]].sort().concat(""AND""); + const intermediateCarryOutput = getOutputForExpr(intermediateCarryExpr); + + let carryExpr = findMatchingExpr(intermediateCarryOutput, ""OR""); + if (carryExpr === null) { + console.log(""TODO""); + } else { + const expectedInputAndOutput = carryExpr[0] === intermediateCarryOutput ? carryExpr[1] : carryExpr[0]; + if (expectedInputAndOutput !== getOutputForExpr(inputAndExpr)) { + swap(getOutputForExpr(inputAndExpr), expectedInputAndOutput); + } + } + + const carryExprSorted = [getOutputForExpr(inputAndExpr), intermediateCarryOutput].sort().concat(""OR""); + const carryOutput = getOutputForExpr(carryExprSorted); + + carries.push(carryOutput); +} + +console.log([...Object.keys(swaps)].sort().join(','));",node:14 +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +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,tqr,vmv,z07,z20,z28","// solution for https://adventofcode.com/2024/day/24 part 2 + +// *NOT* EXPECTING TWO GATES TO HAVE THE SAME OUTPUT WIRE + +// this puzzle is about a circuit for binary sum (x + y = z); +// for each set of three bits (x,y,z) there is a small standard +// circuit of wires and gates that is repeated many times (45 in my input) + +// this small *standard* circuit always starts by connecting a xy bit pair to +// a pair of bottom gates (one gate is AND, the other gate is XOR); any error +// only happens after this part + +// this solution compares each part of the small circuits, searching for the +// misplaced output wires that breaks the *pattern*, level by level + + +""use strict"" + +const input = Deno.readTextFileSync(""day24-input.txt"").trim() + +var xySlotsLength = 0 + +const gatesByOutput = { } + +const gatesByInput = { } + +const misplacedOutputWires = [ ] + + +function main() { + + processInput() + + let gates = processBottomGates() + + while (true) { + + searchMisplacedWires(gates) + + if (misplacedOutputWires.length == 8) { break } + + gates = processNextLevelGates(gates) + } + + console.log(""the answer is"", misplacedOutputWires.sort().join("","")) +} + +/////////////////////////////////////////////////////////////////////////////// + +function processInput() { + + const sections = input.split(""\n\n"") + + xySlotsLength = sections.shift().trim().split(""\n"").length + + // despising xyWires + + const rawGates = sections.shift().trim().split(""\n"") + + for (const rawGate of rawGates) { + + const parts = rawGate.trim().split("" "") + + const wire1 = parts.shift() + const kind = parts.shift() + const wire2 = parts.shift() + parts.shift() // -> + const wire3 = parts.shift() + + processThisInput(kind, wire1, wire2, wire3) + } +} + +function processThisInput(kind, wire1, wire2, wire3) { + + const gate = createGateObj(kind, wire1, wire2, wire3) + + gatesByOutput[wire3] = gate + + if (gatesByInput[wire1] == undefined) { gatesByInput[wire1] = [ ] } + if (gatesByInput[wire2] == undefined) { gatesByInput[wire2] = [ ] } + + gatesByInput[wire1].push(gate) + gatesByInput[wire2].push(gate) +} + +function createGateObj(kind, wire1, wire2, wire3) { + + return { ""kind"": kind, ""wire1"": wire1, ""wire2"": wire2, ""wire3"": wire3, ""paste"": """", ""forward"": """" } +} + +/////////////////////////////////////////////////////////////////////////////// + +function processBottomGates() { + + const bottomGates = new Array(xySlotsLength) + + for (const gate of Object.values(gatesByOutput)) { + + if (gate.wire1[0] != ""x"" && gate.wire1[0] != ""y"") { continue } + + const xySlot = gate.wire1.substr(1) + + const index = (2 * parseInt(xySlot)) + (gate.kind == ""AND"" ? 0 : 1) + + bottomGates[index] = gate + + gate.paste = ""xy"" + + gate.forward = findGateForward(gate.wire3) + } + + return bottomGates +} + +/////////////////////////////////////////////////////////////////////////////// + +function processNextLevelGates(parentList) { + + const childrenList = [ ] + + for (const parent of parentList) { + + const wire = parent.wire3 + + if (wire[0] == ""z"") { continue } + + if (misplacedOutputWires.includes(wire)) { continue } + + const nextGates = gatesByInput[wire] + + for (const nextGate of nextGates) { + + nextGate.paste = parent.paste + "" "" + parent.kind + + nextGate.forward = findGateForward(nextGate.wire3) + + childrenList.push(nextGate) + } + } + + return childrenList +} + +/////////////////////////////////////////////////////////////////////////////// + +function findGateForward(wire) { + + if (wire[0] == ""z"") { return ""FINAL"" } + + const list = [ ] + + for (const destinyGate of gatesByInput[wire]) { list.push(destinyGate.kind) } + + return list.sort().join(""-"") +} + +/////////////////////////////////////////////////////////////////////////////// + +function searchMisplacedWires(gates) { + + const patterns = { } + + for (const gate of gates) { + + const pattern = [ gate.paste, gate.kind, gate.forward ].join("" . "") + + if (isSpecialCase(gate, pattern)) { continue } + + if (patterns[pattern] == undefined) { patterns[pattern] = [ ] } + + patterns[pattern].push(gate.wire3) + } + + for (const list of Object.values(patterns)) { + + if (list.length > 8) { continue } + + for (const wire of list) { misplacedOutputWires.push(wire) } + } +} + +function isSpecialCase(gate, pattern) { + + if (pattern == ""xy . XOR . FINAL"") { return isFirstXYSlot(gate) } + if (pattern == ""xy . AND . AND-XOR"") { return isFirstXYSlot(gate) } + + if (pattern == ""xy AND . OR . FINAL"") { return isLastZSlot(gate) } + + return false +} + +function isFirstXYSlot(gate) { + + return gate.wire1.substr(1) == ""00"" +} + +function isLastZSlot(gate) { + + if (gate.wire3[0] != ""z"") { return false } + + const zSlot = parseInt(gate.wire3.substr(1)) + + return zSlot == xySlotsLength / 2 +} + +/////////////////////////////////////////////////////////////////////////////// + +function show(gates) { + + console.log("""") + for (const gate of gates) { showGate(gate) } +} + +function showGate(gate) { + + // slot is only meaningful for base gates! + + console.log({ ""slot"": gate.wire1.substr(1), ""kind"": gate.kind, ""paste"": gate.paste, ""forward"": gate.forward }) +} + +/////////////////////////////////////////////////////////////////////////////// + +console.time(""execution time"") +main() +console.timeEnd(""execution time"") // 2ms",node:14 +2024,24,2,"--- Day 24: Crossed Wires --- + +You and The Historians arrive at the edge of a large grove somewhere in the jungle. After the last incident, the Elves installed a small device that monitors the fruit. While The Historians search the grove, one of them asks if you can take a look at the monitoring device; apparently, it's been malfunctioning recently. + +The device seems to be trying to produce a number through some boolean logic gates. Each gate has two inputs and one output. The gates all operate on values that are either true (1) or false (0). + +AND gates output 1 if both inputs are 1; if either input is 0, these gates output 0. +OR gates output 1 if one or both inputs is 1; if both inputs are 0, these gates output 0. +XOR gates output 1 if the inputs are different; if the inputs are the same, these gates output 0. +Gates wait until both inputs are received before producing output; wires can carry 0, 1 or no value at all. There are no loops; once a gate has determined its output, the output will not change until the whole system is reset. Each wire is connected to at most one gate output, but can be connected to many gate inputs. + +Rather than risk getting shocked while tinkering with the live system, you write down all of the gate connections and initial wire values (your puzzle input) so you can consider them in relative safety. For example: + +x00: 1 +x01: 1 +x02: 1 +y00: 0 +y01: 1 +y02: 0 + +x00 AND y00 -> z00 +x01 XOR y01 -> z01 +x02 OR y02 -> z02 +Because gates wait for input, some wires need to start with a value (as inputs to the entire system). The first section specifies these values. For example, x00: 1 means that the wire named x00 starts with the value 1 (as if a gate is already outputting that value onto that wire). + +The second section lists all of the gates and the wires connected to them. For example, x00 AND y00 -> z00 describes an instance of an AND gate which has wires x00 and y00 connected to its inputs and which will write its output to wire z00. + +In this example, simulating these gates eventually causes 0 to appear on wire z00, 0 to appear on wire z01, and 1 to appear on wire z02. + +Ultimately, the system is trying to produce a number by combining the bits on all wires starting with z. z00 is the least significant bit, then z01, then z02, and so on. + +In this example, the three output bits form the binary number 100 which is equal to the decimal number 4. + +Here's a larger example: + +x00: 1 +x01: 0 +x02: 1 +x03: 1 +x04: 0 +y00: 1 +y01: 1 +y02: 1 +y03: 1 +y04: 1 + +ntg XOR fgs -> mjb +y02 OR x01 -> tnw +kwq OR kpj -> z05 +x00 OR x03 -> fst +tgd XOR rvg -> z01 +vdt OR tnw -> bfw +bfw AND frj -> z10 +ffh OR nrd -> bqk +y00 AND y03 -> djm +y03 OR y00 -> psh +bqk OR frj -> z08 +tnw OR fst -> frj +gnj AND tgd -> z11 +bfw XOR mjb -> z00 +x03 OR x00 -> vdt +gnj AND wpb -> z02 +x04 AND y00 -> kjc +djm OR pbm -> qhw +nrd AND vdt -> hwm +kjc AND fst -> rvg +y04 OR y02 -> fgs +y01 AND x02 -> pbm +ntg OR kjc -> kwq +psh XOR fgs -> tgd +qhw XOR tgd -> z09 +pbm OR djm -> kpj +x03 XOR y03 -> ffh +x00 XOR y04 -> ntg +bfw OR bqk -> z06 +nrd XOR fgs -> wpb +frj XOR qhw -> z04 +bqk OR frj -> z07 +y03 OR x01 -> nrd +hwm AND bqk -> z03 +tgd XOR rvg -> z12 +tnw OR pbm -> gnj +After waiting for values on all wires starting with z, the wires in this system have the following values: + +bfw: 1 +bqk: 1 +djm: 1 +ffh: 0 +fgs: 1 +frj: 1 +fst: 1 +gnj: 1 +hwm: 1 +kjc: 0 +kpj: 1 +kwq: 0 +mjb: 1 +nrd: 1 +ntg: 0 +pbm: 1 +psh: 1 +qhw: 1 +rvg: 0 +tgd: 0 +tnw: 1 +vdt: 1 +wpb: 0 +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 0 +z05: 1 +z06: 1 +z07: 1 +z08: 1 +z09: 1 +z10: 1 +z11: 0 +z12: 0 +Combining the bits from all wires starting with z produces the binary number 0011111101000. Converting this number to decimal produces 2024. + +Simulate the system of gates and wires. What decimal number does it output on the wires starting with z? + +Your puzzle answer was 52956035802096. + +--- Part Two --- + +After inspecting the monitoring device more closely, you determine that the system you're simulating is trying to add two binary numbers. + +Specifically, it is treating the bits on wires starting with x as one binary number, treating the bits on wires starting with y as a second binary number, and then attempting to add those two numbers together. The output of this operation is produced as a binary number on the wires starting with z. (In all three cases, wire 00 is the least significant bit, then 01, then 02, and so on.) + +The initial values for the wires in your puzzle input represent just one instance of a pair of numbers that sum to the wrong value. Ultimately, any two binary numbers provided as input should be handled correctly. That is, for any combination of bits on wires starting with x and wires starting with y, the sum of the two numbers those bits represent should be produced as a binary number on the wires starting with z. + +For example, if you have an addition system with four x wires, four y wires, and five z wires, you should be able to supply any four-bit number on the x wires, any four-bit number on the y numbers, and eventually find the sum of those two numbers as a five-bit number on the z wires. One of the many ways you could provide numbers to such a system would be to pass 11 on the x wires (1011 in binary) and 13 on the y wires (1101 in binary): + +x00: 1 +x01: 1 +x02: 0 +x03: 1 +y00: 1 +y01: 0 +y02: 1 +y03: 1 +If the system were working correctly, then after all gates are finished processing, you should find 24 (11+13) on the z wires as the five-bit binary number 11000: + +z00: 0 +z01: 0 +z02: 0 +z03: 1 +z04: 1 +Unfortunately, your actual system needs to add numbers with many more bits and therefore has many more wires. + +Based on forensic analysis of scuff marks and scratches on the device, you can tell that there are exactly four pairs of gates whose output wires have been swapped. (A gate can only be in at most one such pair; no gate's output was swapped multiple times.) + +For example, the system below is supposed to find the bitwise AND of the six-bit number on x00 through x05 and the six-bit number on y00 through y05 and then write the result as a six-bit number on z00 through z05: + +x00: 0 +x01: 1 +x02: 0 +x03: 1 +x04: 0 +x05: 1 +y00: 0 +y01: 0 +y02: 1 +y03: 1 +y04: 0 +y05: 1 + +x00 AND y00 -> z05 +x01 AND y01 -> z02 +x02 AND y02 -> z01 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z00 +However, in this example, two pairs of gates have had their output wires swapped, causing the system to produce wrong answers. The first pair of gates with swapped outputs is x00 AND y00 -> z05 and x05 AND y05 -> z00; the second pair of gates is x01 AND y01 -> z02 and x02 AND y02 -> z01. Correcting these two swaps results in this system that works as intended for any set of initial values on wires that start with x or y: + +x00 AND y00 -> z00 +x01 AND y01 -> z01 +x02 AND y02 -> z02 +x03 AND y03 -> z03 +x04 AND y04 -> z04 +x05 AND y05 -> z05 +In this example, two pairs of gates have outputs that are involved in a swap. By sorting their output wires' names and joining them with commas, the list of wires involved in swaps is z00,z01,z02,z05. + +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,tqr,vmv,z07,z20,z28","const fs = require('fs'); + +function collectOutputs(wireValues, prefix) { + return Object.entries(wireValues) + .filter(([key]) => key.startsWith(prefix)) + .sort() + .map(([, value]) => value); +} + +function isInput(operand) { + return operand[0] === 'x' || operand[0] === 'y'; +} + +function getUsageMap(gates) { + const usageMap = {}; + gates.forEach(gate => { + const parts = gate.split(' '); + if (!usageMap[parts[0]]) usageMap[parts[0]] = []; + if (!usageMap[parts[2]]) usageMap[parts[2]] = []; + usageMap[parts[0]].push(gate); + usageMap[parts[2]].push(gate); + }); + return usageMap; +} + +function checkXorConditions(left, right, result, usageMap) { + if (isInput(left)) { + if (!isInput(right) || (result[0] === 'z' && result !== 'z00')) { + return true; + } + const usageOps = (usageMap[result] || []).map(op => op.split(' ')[1]); + if (result !== 'z00' && usageOps.sort().toString() !== ['AND', 'XOR'].toString()) { + return true; + } + } else if (result[0] !== 'z') { + return true; + } + return false; +} + +function checkAndConditions(left, right, result, usageMap) { + if (isInput(left) && !isInput(right)) { + return true; + } + const usageOps = (usageMap[result] || []).map(op => op.split(' ')[1]); + if (usageOps.toString() !== ['OR'].toString()) { + return true; + } + return false; +} + +function checkOrConditions(left, right, result, usageMap) { + if (isInput(left) || isInput(right)) { + return true; + } + const usageOps = (usageMap[result] || []).map(op => op.split(' ')[1]); + if (usageOps.sort().toString() !== ['AND', 'XOR'].toString()) { + return true; + } + return false; +} + +function findSwappedWires(wireValues, gates) { + const usageMap = getUsageMap(gates); + const swappedWires = new Set(); + + gates.forEach(gate => { + const [left, op, right, , result] = gate.split(' '); + if (result === 'z45' || left === 'x00') return; + + if (op === 'XOR' && checkXorConditions(left, right, result, usageMap)) { + swappedWires.add(result); + } else if (op === 'AND' && checkAndConditions(left, right, result, usageMap)) { + swappedWires.add(result); + } else if (op === 'OR' && checkOrConditions(left, right, result, usageMap)) { + swappedWires.add(result); + } else { + console.log(gate, 'unknown op'); + } + }); + + return Array.from(swappedWires).sort(); +} + +function parseInput(fileName) { + const data = fs.readFileSync(fileName, 'utf8').split('\n'); + const wireValues = {}; + const gates = []; + + data.forEach(line => { + const [expr, result] = line.split(' -> '); + if (!result) return; // Skip lines that don't have a valid result + + const [left, op, right] = expr.split(' '); + + if (result && result.startsWith('z')) { + wireValues[result] = 0; // Set default value for z wires + } + + gates.push(`${left} ${op} ${right} -> ${result}`); + }); + + return [wireValues, gates]; +} + +const [wireValues, gates] = parseInput('input.txt'); +const swappedWires = findSwappedWires(wireValues, gates); +const result = swappedWires.join(','); +console.log(result);",node:14 +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"const fs = require('fs'); +const lines = fs.readFileSync('input.txt','utf8') + .trim().split(/\n\s*\n/).map(chunk => chunk.split('\n')); + +function isLock(p) { return p[0] === '#####'; } +function parseLockHeights(p) { + const res = []; + for (let c=0; c<5; c++){ + let h=0; + for (let r=1; r<=5; r++){ + if (p[r][c] === '#') h++; else break; + } + res.push(h); + } + return res; +} + +function parseKeyHeights(p) { + const res = []; + for (let c=0; c<5; c++){ + let h=0; + for (let r=5; r>=1; r--){ + if (p[r][c] === '#') h++; else break; + } + res.push(h); + } + return res; +} + +const locks = [], keys = []; +for (const pat of lines) { + const arr = isLock(pat) ? parseLockHeights(pat) : parseKeyHeights(pat); + isLock(pat) ? locks.push(arr) : keys.push(arr); +} + +let count=0; +for (const lock of locks){ + for (const key of keys){ + if (lock.every((l,i)=>l+key[i]<=5)) count++; + } +} +console.log(count);",node:14 +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"const fs = require(""fs""); +const inputText = ""./input.txt""; + +fs.readFile(inputText, ""utf8"", (err, data) => { + if (err) { + console.error('Error reading file:', err); + return; + } + + const lockKeyData = { + locks: [], + keys: [] + }; + + data.split(""\n\n"").forEach(group => { + const rows = group.split(""\n""); + let topRow = rows.shift().split(""""); + let bottomRow = rows.pop().split(""""); + + let zeroPinHeights = new Array(rows[0].length).fill(0); + const pinHeights = rows.reduce((heights, row) => { + row.split("""").forEach((char, i) => { + if (char === ""#"") heights[i]++; + }); + return heights; + }, zeroPinHeights); + + let isLock = topRow.every(item => item === ""#"") && bottomRow.every(item => item === "".""); + let isKey = topRow.every(item => item === ""."") && bottomRow.every(item => item === ""#""); + if (isLock) lockKeyData.locks.push(pinHeights); + if (isKey) lockKeyData.keys.push(pinHeights); + }) + + console.log(part1(lockKeyData)); + // console.log(part2(data)); + // part2(data); +}); + + +const part1 = (lockKeyData) => { + const { locks, keys } = lockKeyData; + let pairs = 0; + locks.forEach(lock => { + keys.forEach(key => { + const hasOverlap = lock.some((pin, index) => pin + key[index] > 5); + if (!hasOverlap) pairs++; + }); + }); + return pairs; +} + +// const part2 = (data) => {}",node:14 +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"const fs = require('fs'); + +// Read the input file and split by empty lines +const lines = fs.readFileSync('input.txt', 'utf8').trim().split('\n\n'); + +// Function to parse each schematic +function parse(schematic) { + const isLock = schematic[0][0] === ""#""; + const vals = []; + + if (isLock) { + // Lock parsing + for (let j = 0; j < 5; j++) { + for (let i = 0; i < 7; i++) { + if (schematic[i][j] === ""."") { + vals.push(i); + break; + } + } + } + return [vals, isLock]; + } + + // Key parsing + for (let j = 0; j < 5; j++) { + for (let i = 6; i >= 0; i--) { + if (schematic[i][j] === ""."") { + vals.push(6 - i); + break; + } + } + } + return [vals, isLock]; +} + +// Separate locks and keys +const locks = []; +const keys = []; + +lines.forEach(line => { + const [vals, isLock] = parse(line.split(""\n"")); + if (isLock) { + locks.push(vals); + } else { + keys.push(vals); + } +}); + +// Calculate the answer +let ans = 0; +locks.forEach(lock => { + keys.forEach(key => { + let good = true; + + for (let j = 0; j < 5; j++) { + if (lock[j] + key[j] > 7) { + good = false; + break; + } + } + + if (good) ans++; + }); +}); + +console.log(ans);",node:14 +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"const fs = require('fs'); + +// Read the input file and split by empty lines +const lines = fs.readFileSync('input.txt', 'utf8').trim().split('\n\n'); + +// Process the schematics +const schematics = lines.map(line => line.split('\n')); + +let partOne = 0; +const keys = new Set(); +const locks = new Set(); + +schematics.forEach(schematic => { + const isLock = schematic[0][0] === '#'; + const width = schematic[0].length; + + // Transpose the columns + const cols = Array.from({ length: width }, (_, i) => schematic.map(row => row[i])); + + // Calculate heights + const heights = cols.map(c => c.filter(cell => cell === '#').length - 1); + + // Add to locks or keys set + if (isLock) { + locks.add(JSON.stringify(heights)); + } else { + keys.add(JSON.stringify(heights)); + } +}); + +// Compare locks and keys +locks.forEach(lockStr => { + const lock = JSON.parse(lockStr); + keys.forEach(keyStr => { + const key = JSON.parse(keyStr); + const maxKey = lock.map(h => 5 - h); + + if (key.every((h, i) => h <= maxKey[i])) { + partOne += 1; + } + }); +}); + +console.log(""Part One:"", partOne);",node:14 +2024,25,1,"--- Day 25: Code Chronicle --- + +Out of ideas and time, The Historians agree that they should go back to check the Chief Historian's office one last time, just in case he went back there without you noticing. + +When you get there, you are surprised to discover that the door to his office is locked! You can hear someone inside, but knocking yields no response. The locks on this floor are all fancy, expensive, virtual versions of five-pin tumbler locks, so you contact North Pole security to see if they can help open the door. + +Unfortunately, they've lost track of which locks are installed and which keys go with them, so the best they can do is send over schematics of every lock and every key for the floor you're on (your puzzle input). + +The schematics are in a cryptic file format, but they do contain manufacturer information, so you look up their support number. + +""Our Virtual Five-Pin Tumbler product? That's our most expensive model! Way more secure than--"" You explain that you need to open a door and don't have a lot of time. + +""Well, you can't know whether a key opens a lock without actually trying the key in the lock (due to quantum hidden variables), but you can rule out some of the key/lock combinations."" + +""The virtual system is complicated, but part of it really is a crude simulation of a five-pin tumbler lock, mostly for marketing reasons. If you look at the schematics, you can figure out whether a key could possibly fit in a lock."" + +He transmits you some example schematics: + +##### +.#### +.#### +.#### +.#.#. +.#... +..... + +##### +##.## +.#.## +...## +...#. +...#. +..... + +..... +#.... +#.... +#...# +#.#.# +#.### +##### + +..... +..... +#.#.. +###.. +###.# +###.# +##### + +..... +..... +..... +#.... +#.#.. +#.#.# +##### +""The locks are schematics that have the top row filled (#) and the bottom row empty (.); the keys have the top row empty and the bottom row filled. If you look closely, you'll see that each schematic is actually a set of columns of various heights, either extending downward from the top (for locks) or upward from the bottom (for keys)."" + +""For locks, those are the pins themselves; you can convert the pins in schematics to a list of heights, one per column. For keys, the columns make up the shape of the key where it aligns with pins; those can also be converted to a list of heights."" + +""So, you could say the first lock has pin heights 0,5,3,4,3:"" + +##### +.#### +.#### +.#### +.#.#. +.#... +..... +""Or, that the first key has heights 5,0,2,1,3:"" + +..... +#.... +#.... +#...# +#.#.# +#.### +##### +""These seem like they should fit together; in the first four columns, the pins and key don't overlap. However, this key cannot be for this lock: in the rightmost column, the lock's pin overlaps with the key, which you know because in that column the sum of the lock height and key height is more than the available space."" + +""So anyway, you can narrow down the keys you'd need to try by just testing each key with each lock, which means you would have to check... wait, you have how many locks? But the only installation that size is at the North--"" You disconnect the call. + +In this example, converting both locks to pin heights produces: + +0,5,3,4,3 +1,2,0,5,3 +Converting all three keys to heights produces: + +5,0,2,1,3 +4,3,4,0,2 +3,0,2,0,1 +Then, you can try every key with every lock: + +Lock 0,5,3,4,3 and key 5,0,2,1,3: overlap in the last column. +Lock 0,5,3,4,3 and key 4,3,4,0,2: overlap in the second column. +Lock 0,5,3,4,3 and key 3,0,2,0,1: all columns fit! +Lock 1,2,0,5,3 and key 5,0,2,1,3: overlap in the first column. +Lock 1,2,0,5,3 and key 4,3,4,0,2: all columns fit! +Lock 1,2,0,5,3 and key 3,0,2,0,1: all columns fit! +So, in this example, the number of unique lock/key pairs that fit together without overlapping in any column is 3. + +Analyze your lock and key schematics. How many unique lock/key pairs fit together without overlapping in any column?",3162,"const fs = require('fs'); + +// Read the input file +const lines = fs.readFileSync('input.txt', 'utf8').split('\n'); + +// Initialize arrays to hold locks and keys +let locks = []; +let keys = []; + +// Process the schematic data +for (let i = 0; i < lines.length; i += 8) { + const schematic = lines.slice(i + 1, i + 6).map(line => line.trim()); + const schematic_transposed = schematic[0].split('').map((_, index) => schematic.map(row => row[index])); + const pins = schematic_transposed.map(a => a.filter(c => c === '#').length); + + if (lines[i] === '#####') { + locks.push(pins); // lock + } else if (lines[i] === '.....') { + keys.push(pins); // key + } +} + +// Calculate the sum +let sum = 0; +locks.forEach(lock => { + keys.forEach(key => { + const test = lock.map((pin, i) => pin + key[i]); + if (Math.max(...test) < 6) { + sum += 1; + } + }); +}); + +console.log(""Day 25 part 1, sum ="", sum);",node:14 \ No newline at end of file