Skip to main content

Advent of Code - Day 1

· 2 min read
Will Holmes

Code solution

Not my proudest code, but my aim with this day was just to solve it quickly to get the momentum going again. Which it did achieve!

I will say, day 2 was definitley easier than day 1.

Part 1

const fs = require('fs');

function dayTwo() {
const lines = fs.readFileSync('./day2-input.txt', 'utf-8').split('\n');
return lines.reduce((acc, curr) => {
const str = curr.split(':');
const sets = str[1].split(';');
let hasFailed = false;
for (const set of sets) {
if (hasFailed) break;
const colors = {
red: 12, green: 13, blue: 14
}
const entries = set.split(',');
for (const entry of entries) {
const kv = entry.trimStart().split(' ');
colors[kv[1]] = colors[kv[1]] - parseInt(kv[0]);
}
if (Object.values(colors).some(val => val < 0)) {
hasFailed = true;
}
}
if (!hasFailed) {
const gameNumber = parseInt(str[0].split(' ')[1]);
return acc += gameNumber;
} else {
return acc;
}
}, 0);
};

Part 2

function dayTwoPartTwo() {
const lines = fs.readFileSync('./day2-input.txt', 'utf-8').split('\n');
return lines.reduce((acc, curr) => {
const str = curr.split(':');
const sets = str[1].split(';');
const colors = {
red: 0, green: 0, blue: 0
}
for (let i = 0; i < sets.length; i++) {
const set = sets[i];
const entries = set.split(',');
for (const entry of entries) {
const kv = entry.trimStart().split(' ');
if (parseInt(kv[0]) > colors[kv[1]]) {
colors[kv[1]] = parseInt(kv[0]);
}
}
}
return acc += colors.red * colors.green * colors.blue;
}, 0);

Key Takeaways

  1. I love array.reduce for so many common problems.
  2. The solutions are inefficient imo. Looping n games, which have x sets, which have y combintations. Could have done better with time complexity here. But its rough and gets the job done.