advent-of-code

Entries to advent of code, multiple years
git clone git://git.finwo.net/misc/advent-of-code
Log | Files | Refs

commit 247b36212dd6ce2855956d336deedbf0dbd53917
parent 86c5dfa4409581e348bb8027037abdd7ccba9435
Author: finwo <finwo@pm.me>
Date:   Wed, 24 Dec 2025 16:10:54 +0100

Completed 2025/03

Diffstat:
A2025/03/example.txt | 4++++
A2025/03/index.js | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 80 insertions(+), 0 deletions(-)

diff --git a/2025/03/example.txt b/2025/03/example.txt @@ -0,0 +1,4 @@ +987654321111111 +811111111111119 +234234234234278 +818181911112111 diff --git a/2025/03/index.js b/2025/03/index.js @@ -0,0 +1,76 @@ +#!/usr/bin/env node + +const fs = require('node:fs'); + +const banks = fs + .readFileSync('input', 'utf-8') + .split('\r\n').join('\n') + .split('\r').join('\n') + .split('\n') + .map(str => str.trim()) + .filter(str => str) + .map(bank => ({ + batteries: bank, + })) + ; + +// Part 1 +for(const bank of banks) { + // Find the tens + let highestTensVal = -1; + let highestTensIdx = -1; + for(const rating of ['9','8','7','6','5','4','3','2','1']) { + const found = bank.batteries.indexOf(rating); + if (found < 0) continue; + if (found == (bank.batteries.length-1)) continue; + highestTensVal = rating; + highestTensIdx = found; + break; + } + // Find the ones + let highestOnesVal = -1; + let highestOnesIdx = -1; + + for(const rating of ['9','8','7','6','5','4','3','2','1']) { + const found = bank.batteries.indexOf(rating, highestTensIdx+1); + if (found < 0) continue; + highestOnesVal = rating; + highestOnesIdx = found; + break; + } + + // Save it for the records + bank.joltage2 = parseInt(`${highestTensVal}${highestOnesVal}`, 10); +} + +// Part 2 +for(const bank of banks) { + + let construct = []; + let currentIdx = -1; + while(construct.length < 12) { + let found = -1; + for(const rating of ['9','8','7','6','5','4','3','2','1']) { + found = bank.batteries.indexOf(rating, currentIdx + 1); + if (found < 0) continue; + if (found >= (bank.batteries.length + construct.length - 11)) { + found = -1; + continue; + }; + currentIdx = found; + construct.push(rating); + break; + } + if (found < 0) { + throw new Error("Could not find highest number"); + } + } + + bank.joltage12 = BigInt(construct.join('')); +} + +const part1 = banks.reduce((r,bank) => r+bank.joltage2, 0); +const part2 = banks.reduce((r,bank) => r+bank.joltage12, 0n); + +process.stdout.write(`------[ Part 1: ${part1} ]------\n`); +process.stdout.write(`------[ Part 2: ${part2} ]------\n`);