Day 2: Gift Shop

Megathread guidelines

FAQ

  • Zikeji
    link
    fedilink
    English
    arrow-up
    3
    ·
    3 months ago

    Javascript

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

    Solution

    You 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}`);