Advent, the time for glögg and gingersnaps but also coding your heart out. Solving puzzles and surviving a dreadful resort disconnected from everything we know.
I had never heard of advent of code before my friend Emmy told me about it, so as to now shame myself I will try to get as many done as I can (it also very fun when you start).
I will try to display my code and discuss it, however I am not a frequent blogger so some code will be old and sometimes not very well documented/written.
Lets start with day 1!
The puzzle was to solve your expense report, where you had a list of numbers and needed to find two of them that together added up to 2020.
import fs from "fs";
function readData() {
const input = fs.readFileSync("./day1input.txt", { encoding: "utf-8" });
return input.split("\n").map((value) => parseInt(value)).sort((a, b) => a - b);
}
export function day1A(target) {
const data = readData();
const index = data.findIndex((value) => value >= target / );
const upperBoundary = data.slice(index);
const lowerBoundary = data.slice(, index);
console.log("data %s upper %s lower %s", data.length, upperBoundary.length, lowerBoundary.length);
const result = (lowerBoundary.length < upperBoundary.length ? lowerBoundary : upperBoundary).reduce((acc, lowerValue) => {
upperBoundary.forEach((upperValue) => {
if (lowerValue + upperValue === target) {
acc.lower = lowerValue;
acc.upper = upperValue;
}
});
return acc;
}, { lower: , upper: } );
console.log("result", result.lower * result.upper);
}
I made the assumption that to add something from a list, you need to add something above that is greater than or equal to half the target with something lesser than or equal to half the target.
E.g. target is 2020. X + Y = 2020, then X >= 1010 and Y <= 1010.
This worked fine in the first assignment, but did not scale very well in the followup assignment where I needed to add 3 values together. Where the same assumption could not be made. I did not want to create nested for loops, so I kind of skipped this assignment so far, might come back to it.
Who knows ¯\_(ツ)_/¯ not me atleast.