Skip to content

Instantly share code, notes, and snippets.

@Arakade
Created December 5, 2020 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arakade/2dff711fe37abccc500c1d09ecd0eb0f to your computer and use it in GitHub Desktop.
Save Arakade/2dff711fe37abccc500c1d09ecd0eb0f to your computer and use it in GitHub Desktop.
Advent of Code 2020, Day 5 TypeScript (functional style)
// Advent of code 2020, Day 5
import fs from 'fs';
import assert from 'assert';
function convertStringToSeatId(seatCode: string): number {
return (Array.prototype.map.call(seatCode, (c: string): number => {
switch (c) {
case 'F':
case 'L':
return 0;
case 'B':
case 'R':
return 1;
default:
throw new Error(`Invalid character '${c}' in "${seatCode}"`);
}
}) as number[]).reduce((a: number, b: number) => a * 2 + b);
}
const TestCases: [string, number, number, number][] = [
['FBFBBFFRLR', 44, 5, 357], // Part 1
['BFFFBBFRRR', 70, 7, 567],
['FFFBBBFRRR', 14, 7, 119],
['BBFFBBFRLL', 102, 4, 820],
];
for (const tc of TestCases) {
const seatId = convertStringToSeatId(tc[0]);
assert(seatId === tc[3], tc[0]);
}
// Question says not first or last row
const SeatMin = 8,
SeatMax = 8 * 126;
// Skip after finding one since we're only looking for 1 seat
let foundOne = false;
// Go!
const seats = fs
.readFileSync('data/AoC-Day-5-data.txt', 'utf-8')
// Split it up
.split(/[\n\r]/g)
// Remove blank lines (especially trailing)
.filter((s) => 0 < s.length)
// Convert to seat Ids
.map(convertStringToSeatId)
// Sort needs telling not to use char codes!?
.sort((a, b) => a - b)
// Find the one matching the question rule
.filter((id, index, seats) => {
if (foundOne || id < SeatMin || id > SeatMax) return false;
// Use Hannah Rose's (and others') fantastic observation about there being a gap in the sorted seat list
foundOne = 2 === seats[index + 1] - id;
return foundOne;
});
console.log(`seats:${seats.length}:\n`, seats);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment