Skip to content

Instantly share code, notes, and snippets.

@jrsinclair
Created December 2, 2021 00:23
Show Gist options
  • Save jrsinclair/26ee8f01efb25d0980a8ecdab1abfafd to your computer and use it in GitHub Desktop.
Save jrsinclair/26ee8f01efb25d0980a8ecdab1abfafd to your computer and use it in GitHub Desktop.
Advent of Code Day 1 Solution
import fs from 'fs';
const data = fs.readFileSync('/path/to/my/copy/of/input.txt');
const input = data.toString('utf-8').split('\n').filter(x => x !== '').map(x => parseInt(x));
// Chop goes through the array, but gives you less and less of it each time. If you fed it [1, 2, 3], then
// the first iteration would get [1, 2, 3], the next would get [2, 3] and the final would get [3]. Idea is stolen
// from fp-ts: https://gcanti.github.io/fp-ts/modules/ReadonlyArray.ts.html#chop
const chop = (f) => (arr) => [...(new Array(arr.length))].map((_, i) => f(arr.slice(i)));
const sum = (xs) => xs.reduce((a, b) => a + b);
const filter = (pred) => (xs) => xs.filter(pred);
const map = (fn) => (xs) => xs.map(fn);
// Like flow() (which is the reverse of compose()), but the first arg is a value. Mimics method calls, or the
// pipeline operator |>
const pipe = (val, ...fns) => fns.reduce((x, fn) => fn(x), val);
// We could make this with chop(), but this way has fewer loops through the array.
const countIncreases = (xs) => xs.reduce(({prev, count}, next) => {
return {
prev: next,
count: (next > prev) ? count + 1 : count,
}
}, {prev: Number.MAX_SAFE_INTEGER, count: 0}).count;
pipe(
input,
chop(x => x.slice(0, 3)),
filter(x => x.length === 3),
map(sum),
countIncreases
);
// 1491
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment