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
- What is this?: Here is a post with a large amount of details: https://programming.dev/post/6637268
- Where do I participate?: https://adventofcode.com/
- Is there a leaderboard for the community?: We have a programming.dev leaderboard with the info on how to join in this post: https://programming.dev/post/6631465


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