this post was submitted on 02 Dec 2025
24 points (100.0% liked)

Advent Of Code

1154 readers
39 users here now

An unofficial home for the advent of code community on programming.dev! Other challenges are also welcome!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

Everybody Codes is another collection of programming puzzles with seasonal events.

EC 2025

AoC 2025

Solution Threads

M T W T F S S
1 2 3 4 5 6 7
8 9 10 11 12

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 2 years ago
MODERATORS
 

Day 2: Gift Shop

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

you are viewing a single comment's thread
view the rest of the comments
[โ€“] Zikeji@programming.dev 3 points 2 days ago

Javascript

More bruteforcing! There are probably better ways to do this but I'm happy enough with this lol.

SolutionYou can replace the require('fs') on the first line with the input and run it in your browser console as well.

const input = require('fs').readFileSync('input-day2.txt', 'utf-8');

let idsPart1 = [];
let idsPart2 = [];

input.split(',').forEach(range => {
    const [start, end] = range.split('-').map(v => parseInt(v, 10));
    let cursor = start;

    while (cursor <= end) {
        const cursorString = cursor.toString(10);

        // part 1 check
        let halfLength = Math.floor(cursorString.length / 2);
        let left = cursorString.slice(0, halfLength);
        let right = cursorString.slice(halfLength, cursorString.length);
        if (left === right) {
            idsPart1.push(cursor);
        }

        // part 2 check
        let sequenceLength = 1;
        while (sequenceLength <= halfLength) {
            const sequence = cursorString.slice(0, sequenceLength);
            let builtString = sequence;
            while (builtString.length < cursorString.length) {
                builtString = `${builtString}${sequence}`;
            }
            if (builtString === cursorString) {
                idsPart2.push(cursor);
                break;
            }

            sequenceLength += 1;
        }

        cursor += 1;
    }
})

const answer1 = idsPart1.flat().reduce((acc, cur) => acc += cur, 0);
const answer2 = idsPart2.flat().reduce((acc, cur) => acc += cur, 0);

console.log(`Part 1 Answer: ${answer1}`);
console.log(`Part 2 Answer: ${answer2}`);