Files
AoC/2024/14/index2.ts

80 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-12-14 08:26:36 +00:00
const fs = require('fs');
const input = fs.readFileSync(__dirname + '/input.txt', 'utf8');
interface Coord {
x: number,
y: number,
}
interface Bot {
pos: Coord,
vel: Coord,
}
const bots: Array<Bot> = [];
input.split("\n").forEach((line: string) => {
const matches = line.match(/p=(-?\d+),(-?\d+) v=(-?\d+),(-?\d+)/);
if (!matches) {
return;
}
bots.push({
pos: { x: parseInt(matches[1]), y: parseInt(matches[2]) },
vel: { x: parseInt(matches[3]), y: parseInt(matches[4]) },
});
});
const width = 101;
const height = 103;
let seconds = 0;
function printBots() {
const botRows: Array<Array<string>> = [];
for (let y = 0; y < height; y++) {
botRows[y] = [];
for (let x = 0; x < width; x++) {
botRows[y][x] = ' ';
}
}
bots.forEach((bot) => {
botRows[bot.pos.y][bot.pos.x] = '.';
});
console.log(botRows.map((r) => r.join('')).join("\n"));
console.log(seconds);
}
printBots();
function sleep() {
const promise: Promise<void> = new Promise((resolve) => {
setTimeout(() => resolve(), 100);
});
return promise;
}
async function go() {
while (true) {
seconds++;
bots.forEach((bot) => {
let newX = (bot.pos.x + (bot.vel.x)) % width;
if (newX < 0) {
newX = width + newX;
}
bot.pos.x = newX;
let newY = (bot.pos.y + (bot.vel.y)) % height;
if (newY < 0) {
newY = height + newY;
}
bot.pos.y = newY;
});
if ((seconds - 72) % 103 === 0) {
printBots();
await sleep();
}
}
}
go();