Compare commits
11
Commits
16a4bdffd7
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c49253da68 | ||
|
|
0c8efa7aa5 | ||
|
|
ad781d6a6b | ||
|
|
14efab3450 | ||
|
|
835e507816 | ||
|
|
376c7a4532 | ||
|
|
b4052d956f | ||
|
|
f81359618d | ||
|
|
c86bcbffb6 | ||
|
|
35f5601f1e | ||
|
|
08947d2c47 |
No files matched your search
@@ -1,3 +1,3 @@
|
||||
import {runDaySeven} from "./src/day_seven";
|
||||
import {runDayFifteen} from "./src/day_fifteen";
|
||||
|
||||
runDaySeven();
|
||||
runDayFifteen();
|
||||
@@ -0,0 +1,51 @@
|
||||
import {DesertMap, lcm} from "./day_eight";
|
||||
|
||||
describe('Day Eight', () => {
|
||||
const input = `RL
|
||||
|
||||
AAA = (BBB, CCC)
|
||||
BBB = (DDD, EEE)
|
||||
CCC = (ZZZ, GGG)
|
||||
DDD = (DDD, DDD)
|
||||
EEE = (EEE, EEE)
|
||||
GGG = (GGG, GGG)
|
||||
ZZZ = (ZZZ, ZZZ)`;
|
||||
|
||||
const repeatedInput = `LLR
|
||||
|
||||
AAA = (BBB, BBB)
|
||||
BBB = (AAA, ZZZ)
|
||||
ZZZ = (ZZZ, ZZZ)`
|
||||
|
||||
const ghostInput = `LR
|
||||
|
||||
11A = (11B, XXX)
|
||||
11B = (XXX, 11Z)
|
||||
11Z = (11B, XXX)
|
||||
22A = (22B, XXX)
|
||||
22B = (22C, 22C)
|
||||
22C = (22Z, 22Z)
|
||||
22Z = (22B, 22B)
|
||||
XXX = (XXX, XXX)`
|
||||
|
||||
it('should calculate the number of steps needed to reach ZZZ', () => {
|
||||
const map = new DesertMap(input);
|
||||
expect(map.stepsToZ('AAA')).toEqual(2);
|
||||
});
|
||||
|
||||
it('should repeat the pattern', () => {
|
||||
const map = new DesertMap(repeatedInput);
|
||||
expect(map.stepsToZ('AAA')).toEqual(6);
|
||||
});
|
||||
|
||||
it('should count how many steps it takes to get from every node beginning with A, to every node ending in Z simultaneously', () => {
|
||||
const map = new DesertMap(ghostInput);
|
||||
expect(map.ghostStepsToZ()).toEqual(6);
|
||||
});
|
||||
|
||||
describe('lcm', () => {
|
||||
it('should get the correct lowest common multiple', () => {
|
||||
expect(lcm(12, 30)).toEqual(60);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import {anyCharOf, newline, uniDecimal, uniLetter, whitespace} from "parjs";
|
||||
import {between, exactly, manySepBy, manyTill, or, stringify, then} from "parjs/combinators";
|
||||
import fs from "fs";
|
||||
|
||||
const patternParser = anyCharOf("LR").pipe(manyTill(newline().pipe(exactly(2))));
|
||||
|
||||
const nodeNameParser = uniLetter().pipe(or(uniDecimal()), exactly(3), stringify());
|
||||
const childParser = nodeNameParser.pipe(manySepBy(", "), exactly(2), between("(", ")"));
|
||||
const nodeParser = nodeNameParser.pipe(then(childParser.pipe(between(" = ", whitespace()))))
|
||||
|
||||
const parser = patternParser.pipe(then(nodeParser.pipe(manySepBy(whitespace()))));
|
||||
|
||||
type Maybe<T> = T | undefined;
|
||||
|
||||
type Instruction = "L" | "R";
|
||||
type NodeName = string;
|
||||
type NodeChildren = [Maybe<NodeName>, Maybe<NodeName>];
|
||||
|
||||
const gcd = (a: number, b: number): number => {
|
||||
if (b === 0) return a;
|
||||
return gcd(b, a % b);
|
||||
}
|
||||
|
||||
export const lcm = (a: number, b: number): number => {
|
||||
const product = a * b;
|
||||
return product / gcd(a, b);
|
||||
}
|
||||
|
||||
export class DesertMap {
|
||||
private readonly pattern: Instruction[];
|
||||
|
||||
private map: Record<NodeName, NodeChildren> = {};
|
||||
|
||||
constructor(input: string) {
|
||||
const [pattern, nodes] = parser.parse(input).value;
|
||||
|
||||
this.pattern = pattern as Instruction[];
|
||||
|
||||
for (const [name, [[leftNode, rightNode]]] of nodes) {
|
||||
if (!this.map[name]) {
|
||||
this.map[name] = [undefined, undefined];
|
||||
}
|
||||
const children = [leftNode, rightNode];
|
||||
this.map[name] = children as NodeChildren;
|
||||
}
|
||||
}
|
||||
|
||||
public stepsToZ(from: string): number {
|
||||
let step = 0;
|
||||
let curr = from;
|
||||
|
||||
while (!curr.endsWith('Z')) {
|
||||
const instruction = this.pattern[step % this.pattern.length];
|
||||
|
||||
const [left, right] = this.map[curr];
|
||||
|
||||
if (instruction === "L" && left) {
|
||||
curr = left;
|
||||
} else if (instruction === "R" && right) {
|
||||
curr = right;
|
||||
}
|
||||
|
||||
if (!curr) return 0;
|
||||
|
||||
step++;
|
||||
}
|
||||
return step;
|
||||
}
|
||||
|
||||
public ghostStepsToZ(): number {
|
||||
let keys = Object.keys(this.map).filter(key => key.endsWith('A'));
|
||||
|
||||
return keys.map(key => this.stepsToZ(key)).reduce(lcm);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export const runDayEight = () => {
|
||||
const input = fs.readFileSync('./inputs/day_eight_input.txt', 'utf-8').trimEnd();
|
||||
|
||||
const map = new DesertMap(input);
|
||||
console.log(map.stepsToZ('AAA'));
|
||||
|
||||
console.log(map.ghostStepsToZ());
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import {Observatory} from "./day_eleven";
|
||||
|
||||
describe('Observatory', () => {
|
||||
const input = `...#......
|
||||
.......#..
|
||||
#.........
|
||||
..........
|
||||
......#...
|
||||
.#........
|
||||
.........#
|
||||
..........
|
||||
.......#..
|
||||
#...#.....`;
|
||||
|
||||
it('should calculate the shortest path between every galaxy', () => {
|
||||
const observatory = new Observatory(input);
|
||||
expect(observatory.shortestPaths).toEqual(82000210);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[[9, 0], [9, 4], 1_000_004],
|
||||
[[0, 3], [8, 7], 3_000_012],
|
||||
])(`should calculate the distance between two galaxies`, (galaxyOne, galaxyTwo, expectedDistance) => {
|
||||
const observatory = new Observatory(input);
|
||||
expect(observatory.distanceBetween(galaxyOne as [number, number], galaxyTwo as [number, number])).toEqual(expectedDistance);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import {Range, Seq, Set} from "immutable";
|
||||
import fs from "fs";
|
||||
|
||||
type Position = [number, number];
|
||||
type GalaxyPair = [Position, Position];
|
||||
|
||||
export class Observatory {
|
||||
private grid: string[][] = [];
|
||||
private expandedRows: number[] = [];
|
||||
private expandedColumns: number[] = [];
|
||||
|
||||
constructor(input: string) {
|
||||
this.grid = input.split('\n').map(line => line.split(''));
|
||||
|
||||
this.expandGrid();
|
||||
}
|
||||
|
||||
private expandGrid() {
|
||||
this.expandedColumns = Range(0, this.grid[0].length).filter(column => this.grid.every(row => row[column] === '.')).toArray();
|
||||
this.expandedRows = Range(0, this.grid.length).filter(row => this.grid[row].every(column => column === '.')).toArray();
|
||||
}
|
||||
|
||||
public get shortestPaths(): number {
|
||||
const distances = this.pairs.map(pair => this.distanceBetween(pair[0], pair[1]));
|
||||
return distances.reduce((sum, distance) => sum + distance, 0);
|
||||
}
|
||||
|
||||
private get pairs(): GalaxyPair[] {
|
||||
const galaxies = this.grid.reduce((galaxies, row, rowIndex) => {
|
||||
row.forEach((galaxy, columnIndex) => {
|
||||
if (galaxy === '#') {
|
||||
galaxies.push([rowIndex, columnIndex]);
|
||||
}
|
||||
});
|
||||
return galaxies;
|
||||
}, [] as Position[]);
|
||||
|
||||
return galaxies.reduce((pairs, galaxy, index) => {
|
||||
return pairs.withMutations(pairs => {
|
||||
galaxies.slice(index + 1).forEach(otherGalaxy => {
|
||||
pairs.add([galaxy, otherGalaxy]);
|
||||
});
|
||||
})
|
||||
}, Set<GalaxyPair>()).toArray();
|
||||
}
|
||||
|
||||
private range = (a: number, b: number): Seq.Indexed<number> => {
|
||||
return Range(Math.min(a, b), Math.max(a, b) + 1);
|
||||
}
|
||||
public distanceBetween(galaxyOne: Position, galaxyTwo: Position): number {
|
||||
const expansion = 999_999;
|
||||
|
||||
const xRange = this.range(galaxyOne[0], galaxyTwo[0]).filter(row => this.expandedRows.includes(row)).toArray().length;
|
||||
const yRange = this.range(galaxyOne[1], galaxyTwo[1]).filter(column => this.expandedColumns.includes(column)).toArray().length;
|
||||
|
||||
const expansions = expansion * (xRange + yRange)
|
||||
|
||||
return Math.abs(galaxyOne[0] - galaxyTwo[0]) + Math.abs(galaxyOne[1] - galaxyTwo[1]) + expansions;
|
||||
}
|
||||
}
|
||||
|
||||
export const runDayEleven = () => {
|
||||
const input = fs.readFileSync('./inputs/day_eleven_input.txt', 'utf-8').trimEnd();
|
||||
const observatory = new Observatory(input);
|
||||
console.log(`The shortest path between every galaxy is ${observatory.shortestPaths}`);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import {totalFocusingPower, hash, hashSum} from "./day_fifteen";
|
||||
|
||||
describe('Day Fifteen', () => {
|
||||
it.each([
|
||||
['HASH', 52],
|
||||
['rn=1', 30],
|
||||
['cm-', 253],
|
||||
['qp=3', 97],
|
||||
['cm=2', 47],
|
||||
['qp-', 14],
|
||||
['pc=4', 180],
|
||||
['ot=9', 9],
|
||||
['ab=5', 197],
|
||||
['pc-', 48],
|
||||
['pc=6', 214],
|
||||
['ot=7', 231],
|
||||
])('calculates the hash of %s to %s', (input, expected) => {
|
||||
expect(hash(input)).toBe(expected);
|
||||
});
|
||||
|
||||
it('calculates the hash of the example', () => {
|
||||
const input = 'rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7';
|
||||
expect(hashSum(input)).toEqual(1320);
|
||||
});
|
||||
|
||||
it('calculates the focusing power', () => {
|
||||
const input = 'rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7';
|
||||
expect(totalFocusingPower(input)).toEqual(145);
|
||||
})
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import fs from "fs";
|
||||
|
||||
export const hash = (input: string): number => {
|
||||
const parts = input.split('');
|
||||
let hash = 0;
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
hash += parts[i].charCodeAt(0);
|
||||
hash *= 17;
|
||||
hash %= 256;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
export const hashSum = (input: string): number => {
|
||||
return input.split(',').reduce((sum, part) => sum + hash(part), 0);
|
||||
}
|
||||
|
||||
|
||||
const focusingPower = (boxNumber: number, slot: number, value: number): number => {
|
||||
return (1 + boxNumber) * (1 + slot) * value;
|
||||
}
|
||||
|
||||
export const totalFocusingPower = (input: string): number => {
|
||||
const boxes: [string, number][][] = new Array(256).fill(0).map(() => []);
|
||||
|
||||
input.split(',').forEach(part => {
|
||||
if (part.includes('=')) {
|
||||
const [label, value] = part.split('=');
|
||||
const box = hash(label);
|
||||
const index = boxes[box].findIndex(([l]) => l === label);
|
||||
boxes[hash(label)].splice(index === -1 ? boxes[box].length : index, 1, [label, parseInt(value)]);
|
||||
} else {
|
||||
const [label] = part.split('-');
|
||||
let box = hash(label);
|
||||
const index = boxes[box].findIndex(([l]) => l === label);
|
||||
if (index !== -1) {
|
||||
boxes[box].splice(index, 1);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return boxes.reduce(
|
||||
(sum, box, boxIndex) =>
|
||||
sum + box.reduce(
|
||||
(total, [label, value], slot) => {
|
||||
return total + focusingPower(boxIndex, slot, value)
|
||||
},
|
||||
0
|
||||
),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
export const runDayFifteen = () => {
|
||||
const input = fs.readFileSync('./inputs/day_fifteen_input.txt', 'utf-8').trimEnd();
|
||||
console.log('Day Fifteen output:', totalFocusingPower(input));
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import {mapSeedToLocation} from "./day_five";
|
||||
|
||||
describe('Day Five', () => {
|
||||
const input = `seeds: 79 14 55 13
|
||||
|
||||
seed-to-soil map:
|
||||
50 98 2
|
||||
52 50 48
|
||||
|
||||
soil-to-fertilizer map:
|
||||
0 15 37
|
||||
37 52 2
|
||||
39 0 15
|
||||
|
||||
fertilizer-to-water map:
|
||||
49 53 8
|
||||
0 11 42
|
||||
42 0 7
|
||||
57 7 4
|
||||
|
||||
water-to-light map:
|
||||
88 18 7
|
||||
18 25 70
|
||||
|
||||
light-to-temperature map:
|
||||
45 77 23
|
||||
81 45 19
|
||||
68 64 13
|
||||
|
||||
temperature-to-humidity map:
|
||||
0 69 1
|
||||
1 0 69
|
||||
|
||||
humidity-to-location map:
|
||||
60 56 37
|
||||
56 93 4`;
|
||||
|
||||
it('should calculate the smallest location from the input', () => {
|
||||
const result = mapSeedToLocation(input);
|
||||
expect(result).toEqual(46);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import {Range, Seq} from "immutable";
|
||||
import {chunk} from "lodash";
|
||||
import fs from "fs";
|
||||
|
||||
type MapRange = {
|
||||
source: number;
|
||||
destination: number;
|
||||
size: number;
|
||||
}
|
||||
|
||||
const parseSeeds = (input: string): Seq.Indexed<number> => {
|
||||
const [_, seedString] = input.split('seeds: ');
|
||||
|
||||
return chunk(seedString.split(' '), 2).reduce((seeds, [start, size]) => {
|
||||
return seeds.concat(Range(Number(start), Number(start) + Number(size)));
|
||||
}, Seq.Indexed<number>());
|
||||
}
|
||||
|
||||
const mapMapper = (input: string): MapRange[] => {
|
||||
const [_, ...lines] = input.split('\n');
|
||||
|
||||
return lines.map(line => {
|
||||
const [dest, source, size] = line.split(' ').map(Number);
|
||||
return {
|
||||
source: source,
|
||||
destination: dest,
|
||||
size
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const seedMapper = (seed: number, map: MapRange[]): number => {
|
||||
const mapped = map.find(({source, destination, size}) => {
|
||||
return seed >= source && seed < source + size;
|
||||
});
|
||||
|
||||
if (!mapped) {
|
||||
return seed;
|
||||
}
|
||||
|
||||
return seed - mapped.source + mapped.destination;
|
||||
}
|
||||
|
||||
export const mapSeedToLocation = (input: string): number => {
|
||||
const [seedsStr, ...mapStrings] = input.split('\n\n');
|
||||
const seeds = parseSeeds(seedsStr);
|
||||
|
||||
const maps = mapStrings.map(mapMapper);
|
||||
|
||||
const mapped = seeds.map(seed => {
|
||||
return maps.reduce((seed, map) => seedMapper(seed, map), seed);
|
||||
});
|
||||
|
||||
return mapped.min()!;
|
||||
}
|
||||
|
||||
export const runDayFive = () => {
|
||||
const input = fs.readFileSync('./inputs/day_five_input.txt', 'utf8').trimEnd();
|
||||
const result = mapSeedToLocation(input);
|
||||
console.log(`Day Five: ${result}`);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import {Oasis} from "./day_nine";
|
||||
|
||||
describe('Day Nine', () => {
|
||||
const input = `0 3 6 9 12 15
|
||||
1 3 6 10 15 21
|
||||
10 13 16 21 30 45`;
|
||||
|
||||
it.each([
|
||||
[[0, 3, 6, 9, 12, 15], 18],
|
||||
[[1, 3, 6, 10, 15, 21], 28],
|
||||
[[10, 13, 16, 21, 30, 45], 68]
|
||||
])('It should get the next value in the sequence', (sequence, expected) => {
|
||||
const oasis = new Oasis(input);
|
||||
expect(oasis.getNextValueInSequence(sequence)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('should get the total of the next values in each sequence', () => {
|
||||
const oasis = new Oasis(input);
|
||||
expect(oasis.getTotalOfNextValuesInSequences()).toEqual(114);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[[0, 3, 6, 9, 12, 15], -3],
|
||||
[[1, 3, 6, 10, 15, 21], 0],
|
||||
[[10, 13, 16, 21, 30, 45], 5]
|
||||
])('It should get the previous value in the sequence', (sequence, expected) => {
|
||||
const oasis = new Oasis(input);
|
||||
expect(oasis.getPreviousValueInSequence(sequence)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('should get the total of the previous values in each sequence', () => {
|
||||
const oasis = new Oasis(input);
|
||||
expect(oasis.getTotalOfPreviousValuesInSequences()).toEqual(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import fs from "fs";
|
||||
|
||||
export class Oasis {
|
||||
private readonly sequences: number[][];
|
||||
|
||||
constructor(input: string) {
|
||||
this.sequences = input.split('\n').map(line => line.split(' ').map(Number));
|
||||
}
|
||||
|
||||
public getNextValueInSequence(seq: number[]): number {
|
||||
if (new Set(seq).size === 1) return seq[0];
|
||||
const differences = seq.reduce((acc: number[], curr, i, arr) => {
|
||||
if (i === 0) return acc;
|
||||
acc.push(curr - arr[i - 1]);
|
||||
return acc;
|
||||
}, []);
|
||||
return this.getNextValueInSequence(differences) + seq[seq.length - 1];
|
||||
}
|
||||
|
||||
public getPreviousValueInSequence(seq: number[]): number {
|
||||
if (new Set(seq).size === 1) return seq[0];
|
||||
const differences = seq.reduce((acc: number[], curr, i, arr) => {
|
||||
if (i === 0) return acc;
|
||||
acc.push(curr - arr[i - 1]);
|
||||
return acc;
|
||||
}, []);
|
||||
return seq[0] - this.getPreviousValueInSequence(differences);
|
||||
}
|
||||
|
||||
public getTotalOfNextValuesInSequences(): number {
|
||||
return this.sequences.reduce((acc, curr) => acc + this.getNextValueInSequence(curr), 0);
|
||||
}
|
||||
|
||||
public getTotalOfPreviousValuesInSequences(): number {
|
||||
return this.sequences.reduce((acc, curr) => acc + this.getPreviousValueInSequence(curr), 0);
|
||||
}
|
||||
}
|
||||
|
||||
export const runDayNine = () => {
|
||||
const input = fs.readFileSync('./inputs/day_nine_input.txt', 'utf-8').trimEnd();
|
||||
const oasis = new Oasis(input);
|
||||
console.log(oasis.getTotalOfNextValuesInSequences());
|
||||
console.log(oasis.getTotalOfPreviousValuesInSequences());
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import {getFurthestDistance, tilesContained} from "./day_ten";
|
||||
|
||||
describe('Day Ten', () => {
|
||||
it.each([
|
||||
[`.....
|
||||
.S-7.
|
||||
.|.|.
|
||||
.L-J.
|
||||
.....`, 4], [
|
||||
`-L|F7
|
||||
7S-7|
|
||||
L|7||
|
||||
-L-J|
|
||||
L|-JF`, 4],
|
||||
[`..F7.
|
||||
.FJ|.
|
||||
SJ.L7
|
||||
|F--J
|
||||
LJ...`, 8]
|
||||
])('should calculate the number of steps to the exit', (input, expected) => {
|
||||
const result = getFurthestDistance(input);
|
||||
expect(result).toEqual(expected);
|
||||
});
|
||||
|
||||
describe('Part Two', () => {
|
||||
it.each([
|
||||
['.....\n' +
|
||||
'.S-7.\n' +
|
||||
'.|.|.\n' +
|
||||
'.L-J.\n' +
|
||||
'.....', 1],
|
||||
['...........\n' +
|
||||
'.S-------7.\n' +
|
||||
'.|F-----7|.\n' +
|
||||
'.||.....||.\n' +
|
||||
'.||.....||.\n' +
|
||||
'.|L-7.F-J|.\n' +
|
||||
'.|..|.|..|.\n' +
|
||||
'.L--J.L--J.\n' +
|
||||
'...........\n', 4],
|
||||
['.F----7F7F7F7F-7....\n' +
|
||||
'.|F--7||||||||FJ....\n' +
|
||||
'.||.FJ||||||||L7....\n' +
|
||||
'FJL7L7LJLJ||LJ.L-7..\n' +
|
||||
'L--J.L7...LJS7F-7L7.\n' +
|
||||
'....F-J..F7FJ|L7L7L7\n' +
|
||||
'....L7.F7||L7|.L7L7|\n' +
|
||||
'.....|FJLJ|FJ|F7|.LJ\n' +
|
||||
'....FJL-7.||.||||...\n' +
|
||||
'....L---J.LJ.LJLJ...', 8],
|
||||
['FF7FSF7F7F7F7F7F---7\n' +
|
||||
'L|LJ||||||||||||F--J\n' +
|
||||
'FL-7LJLJ||||||LJL-77\n' +
|
||||
'F--JF--7||LJLJ7F7FJ-\n' +
|
||||
'L---JF-JLJ.||-FJLJJ7\n' +
|
||||
'|F|F-JF---7F7-L7L|7|\n' +
|
||||
'|FFJF7L7F-JF7|JL---7\n' +
|
||||
'7-L-JL7||F7|L7F-7F7|\n' +
|
||||
'L.L7LFJ|||||FJL7||LJ\n' +
|
||||
'L7JLJL-JLJLJL--JLJ.L', 10]
|
||||
])('should count the number of tiles fully contained within the loop', (input, expected) => {
|
||||
// const result = tilesContained(input);
|
||||
const result = tilesContained(input);
|
||||
expect(result).toEqual(expected);
|
||||
})
|
||||
});
|
||||
});
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import fs from "fs";
|
||||
import {window} from "./utils";
|
||||
|
||||
type Grid = Tile[][];
|
||||
type Cell = [number, number];
|
||||
type Tile = 'S' | 'F' | 'J' | 'L' | '7' | '-' | '|' | '.';
|
||||
type Loop = string[];
|
||||
|
||||
const isTile = (value: string): value is Tile => {
|
||||
return ['S', 'F', 'J', 'L', '7', '-', '|', '.'].includes(value);
|
||||
}
|
||||
|
||||
const toString = (cell: Cell): string => {
|
||||
return JSON.stringify(cell);
|
||||
}
|
||||
|
||||
const fromString = (cell: string): Cell => {
|
||||
return JSON.parse(cell);
|
||||
}
|
||||
|
||||
|
||||
const getStart = (grid: Grid): Cell => {
|
||||
const row = grid.findIndex(row => row.includes('S'));
|
||||
const col = grid[row].findIndex(cell => cell === 'S');
|
||||
return [row, col];
|
||||
}
|
||||
|
||||
const getSurrounding = (grid: Grid, [row, col]: Cell): Cell[] => {
|
||||
return ([
|
||||
[row - 1, col],
|
||||
[row + 1, col],
|
||||
[row, col - 1],
|
||||
[row, col + 1],
|
||||
[row - 1, col - 1],
|
||||
[row - 1, col + 1],
|
||||
[row + 1, col - 1],
|
||||
[row + 1, col + 1],
|
||||
] as Cell[]).filter((cell) => isInGrid(grid, cell));
|
||||
}
|
||||
const getConnectingNeighbours = (grid: Grid, [row, col]: Cell): Cell[] => {
|
||||
return getSurrounding(grid, [row, col]).filter((cell) =>
|
||||
isValid(grid, cell) && neighbours(grid, cell).map(toString).includes(toString([row, col]))
|
||||
);
|
||||
}
|
||||
|
||||
const neighbours = (grid: Grid, [row, col]: Cell): Cell[] => {
|
||||
const value = grid[row][col];
|
||||
switch (value) {
|
||||
case 'F':
|
||||
return [
|
||||
[row, col + 1],
|
||||
[row + 1, col],
|
||||
];
|
||||
case 'J':
|
||||
return [
|
||||
[row - 1, col],
|
||||
[row, col - 1]
|
||||
];
|
||||
case 'L':
|
||||
return [
|
||||
[row, col + 1],
|
||||
[row - 1, col]
|
||||
];
|
||||
case '7':
|
||||
return [
|
||||
[row + 1, col],
|
||||
[row, col - 1]
|
||||
];
|
||||
case '-':
|
||||
return [
|
||||
[row, col + 1],
|
||||
[row, col - 1]
|
||||
];
|
||||
case '|':
|
||||
return [
|
||||
[row - 1, col],
|
||||
[row + 1, col]
|
||||
];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function isInGrid(grid: Tile[][], [row, col]: Cell) {
|
||||
return row >= 0 && row < grid.length && col >= 0 && col < grid[row].length;
|
||||
}
|
||||
|
||||
const isValid = (grid: Grid, cell: Cell): boolean => {
|
||||
return isInGrid(grid, cell) && grid[cell[0]][cell[1]] !== '.';
|
||||
}
|
||||
|
||||
function parseGrid(input: string) {
|
||||
return input.split('\n').map(line => line.split('').filter(isTile));
|
||||
}
|
||||
|
||||
function getMainLoop(grid: Grid): Loop {
|
||||
const start = getStart(grid);
|
||||
const queue = [getConnectingNeighbours(grid, start)[0]];
|
||||
const visited = [toString(start)];
|
||||
|
||||
while (queue.length > 0) {
|
||||
const current = queue.shift()!;
|
||||
const next = neighbours(grid, current);
|
||||
|
||||
next.forEach(cell => {
|
||||
if (!visited.includes(toString(cell)) && isValid(grid, cell)) {
|
||||
queue.push(cell);
|
||||
visited.push(toString(cell));
|
||||
}
|
||||
});
|
||||
}
|
||||
return visited;
|
||||
}
|
||||
|
||||
export const getFurthestDistance = (input: string): number => {
|
||||
const grid = parseGrid(input);
|
||||
const loop = getMainLoop(grid);
|
||||
|
||||
return loop.length / 2;
|
||||
}
|
||||
|
||||
export const area = (grid: Grid, loop: Loop): number => {
|
||||
// Use shoelace formula to calculate area of polygon
|
||||
const polygon = loop.map(fromString).filter((cell) => {
|
||||
const value = grid[cell[0]][cell[1]];
|
||||
return ['F', 'J', 'L', '7', 'S'].includes(value);
|
||||
});
|
||||
|
||||
const total = window([...polygon, polygon[0]], 2).reduce((total, [a, b]) => {
|
||||
const [y1, x1] = a;
|
||||
const [y2, x2] = b;
|
||||
return total + (x1 * y2 - y1 * x2);
|
||||
}, 0);
|
||||
|
||||
return Math.abs(total) / 2;
|
||||
}
|
||||
|
||||
export const tilesContained = (input: string): number => {
|
||||
const grid = parseGrid(input);
|
||||
const loop = getMainLoop(grid);
|
||||
|
||||
const loopArea = area(grid, loop);
|
||||
const boundaryPointsCount = loop.length;
|
||||
return loopArea - (boundaryPointsCount / 2) + 1;
|
||||
}
|
||||
|
||||
export const runDayTen = () => {
|
||||
const input = fs.readFileSync('./inputs/day_ten_input.txt', 'utf8').trimEnd();
|
||||
const result = tilesContained(input);
|
||||
console.log(`Day Ten: ${result}`);
|
||||
}
|
||||
@@ -5,3 +5,10 @@ export const matchAllAndThen = (input: string, pattern: RegExp, callback: (value
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export const window = <T>(input: T[], size: number): T[][] => {
|
||||
return input.reduce((windows, value, index) => {
|
||||
if (index === input.length - size + 1) return windows;
|
||||
return [...windows, input.slice(index, index + size)];
|
||||
}, [] as T[][]);
|
||||
}
|
||||
Reference in new issue
Block a user