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

  • Zikeji@programming.dev
    link
    fedilink
    English
    arrow-up
    3
    ·
    4 days 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}`);