Skip to content

Instantly share code, notes, and snippets.

@bluepichu
Created December 20, 2021 05:19
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 bluepichu/a399a660ff656526e2516d2b1a63832f to your computer and use it in GitHub Desktop.
Save bluepichu/a399a660ff656526e2516d2b1a63832f to your computer and use it in GitHub Desktop.
import { List, Map, Set } from "immutable";
import { Advent, arr } from "advent";
const { compute, computeCheck } = await Advent({ day: 20 });
compute(async (input) => {
// const data = input.tokens(/,/).map(int);
const [alg, imageStr] = input.all().split("\n\n");
let image = imageStr.split("\n").map((c) => c.split(""));
for (let i = 0; i < 50; i++) {
image = enhance(image, alg, i % 2 == 0 ? "." : "#");
}
return image.reduce((acc, line) => acc + line.reduce((a, c) => c === "#" ? a + 1 : a, 0), 0);
}, 2);
function pad(image: string[][], padWith: string) {
let out = arr(image.length + 2, () => arr(image[0].length + 2, () => padWith));
for (let i = 0; i < image.length; i++) {
for (let j = 0; j < image[i].length; j++) {
out[i + 1][j + 1] = image[i][j];
}
}
return out;
}
function enhance(image: string[][], alg: string, padWith: string) {
image = pad(pad(image, padWith), padWith);
let out = arr(image.length, () => arr(image[0].length, () => "."));
for (let i = 0; i < image.length; i++) {
for (let j = 0; j < image.length; j++) {
let val = 0;
for (let di of [-1, 0, 1]) {
for (let dj of [-1, 0, 1]) {
val *= 2;
if (
i + di >= 0 &&
i + di < image.length &&
j + dj >= 0 &&
j + dj < image[i].length
) {
if (image[i + di][j + dj] === "#") {
val++;
}
} else if (padWith === "#") {
val++;
}
}
}
out[i][j] = alg[val];
}
}
return out;
}
function show(image: string[][]) {
console.log("\n".repeat(3));
for (let line of image) {
console.log(line.join(""));
}
}
// computeCheck(async function* (input) {
// yield 0;
// });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment