Day 1: Secret Entrance

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
[โ€“] 4 points 9 months ago (1 child)

A straightforward day 1 for a Javascript / NodeJS solution.

Poorly Optimized JS Solution

let position = 50;
let answer1 = 0;
let answer2 = 0;

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

sequence.split('\n').forEach(instruction => {
    const turn = instruction.charAt(0);
    let distance = parseInt(instruction.slice(1), 10);

    while (distance > 0) {
        distance -= 1;

        if (turn === 'L') {
            position -= 1;
        } else if (turn === 'R') {
            position += 1;
        }

        if (position >= 100) {
            position -= 100;
        } else if (position < 0) {
            position += 100;
        }

        if (position === 0) {
            answer2 += 1;
        }
    }

    if (position === 0) {
        answer1 += 1;
    }
});

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

  • source
  • hideshow 1 child comment