Merge branch '2021-11'

This commit is contained in:
Yanick Champoux 2021-12-11 12:08:44 -05:00
commit 11246d2749
4 changed files with 120 additions and 0 deletions

68
2021/11/part1.mjs Normal file
View File

@ -0,0 +1,68 @@
import fs from "fs-extra";
import fp from "lodash/fp.js";
import _ from "lodash";
export const processInput = (file) =>
fs.readFile(file, "utf8").then((content) =>
content
.split("\n")
.filter((x) => x)
.map((line) => line.split("").map((x) => parseInt(x)))
);
export const genNeighbours = (maxX, maxY) => (x, y) =>
[
[-1, 0],
[1, 0],
[0, 1],
[0, -1],
[1, 1],
[-1, -1],
[1, -1],
[-1, 1],
]
.map((delta) => _.zip(delta, [x, y]).map(_.sum))
.filter(([x, y]) => {
if (x < 0 || y < 0) return false;
if (x >= maxX || y >= maxY) return false;
return true;
});
function powerUp(x, y, grid, toClear) {
grid[x][y]++;
if (grid[x][y] !== 10) return 0;
// FLASH!
toClear.push([x, y]);
return _.sum([
1,
...genNeighbours(grid.length, grid[0].length)(x, y).map((coords) =>
powerUp(...coords, grid, toClear)
),
]);
}
export function playTurn(grid) {
let flashes = 0;
let toClear = [];
for (const x in grid) {
for (const y in grid[x]) {
flashes += powerUp(parseInt(x), parseInt(y), grid, toClear);
}
}
for (const [x, y] of toClear) {
grid[x][y] = 0;
}
return flashes;
}
export const printGrid = (grid) =>
grid.forEach((line) => console.log(line.join("")));
export const solution = (grid) =>
_.sum(_.range(100).map(() => playTurn(grid)));

19
2021/11/part2.mjs Normal file
View File

@ -0,0 +1,19 @@
import fs from "fs-extra";
import fp from "lodash/fp.js";
import _ from "lodash";
import * as p1 from './part1.mjs';
const allFlashed = grid => grid.every(
row => row.every( x => x === 0 )
);
export function solution(grid) {
let step = 0;
while(true) {
step++;
p1.playTurn(grid);
if( allFlashed(grid) ) return step;
}
}

10
2021/11/sample Normal file
View File

@ -0,0 +1,10 @@
5483143223
2745854711
5264556173
6141336146
6357385478
4167524645
2176841721
6882881134
4846848554
5283751526

23
2021/11/test.mjs Normal file
View File

@ -0,0 +1,23 @@
// https://adventofcode.com/2021/day/11
import tap from "tap";
import fs from "fs-extra";
import * as p1 from "./part1.mjs";
import * as p2 from "./part2.mjs";
tap.test("part1", async (t) => {
const sample = p1.processInput('sample');
const input = p1.processInput('input');
t.equal(p1.solution(await sample), 1656);
t.equal(p1.solution(await input), 1729);
});
tap.test("part2", async (t) => {
const sample = await p1.processInput('sample');
const input = await p1.processInput('input');
t.equal(p2.solution(sample), 195);
t.equal(p2.solution(input), 237);
});