Skip to content

Instantly share code, notes, and snippets.

@ablamunits
Last active December 11, 2021 14:45
Show Gist options
  • Save ablamunits/201be521399d6bbc1d4f1beffb141417 to your computer and use it in GitHub Desktop.
Save ablamunits/201be521399d6bbc1d4f1beffb141417 to your computer and use it in GitHub Desktop.
export const runNStepsOfSimultation = (grid: Cell[][], n: number): number => {
let flashesCount = 0;
for (let step = 0; step < n; step++) {
const q: Cell[] = [];
// Increase all
grid.forEach((row) => row.forEach(cell => cell.increase()));
// Add naighbours to queue
grid.forEach((row) => row.forEach((cell) => {
if (cell.value === 0) {
flashesCount++;
getNonFlashingCellNaighbours(cell, grid).forEach(n => q.unshift(n));
}
}))
while(q.length) {
const cell = q.pop();
if (cell.value !== 0) {
cell.increase();
if (cell.value === 0) {
flashesCount++;
getNonFlashingCellNaighbours(cell, grid).forEach(n => q.unshift(n));
}
}
}
}
return flashesCount;
}
export const solveP1 = (input: string) => {
const grid = parseInput(input);
// Run simulation for 100 steps
return runNStepsOfSimultation(grid, 100);
};
export const solveP2 = (input: string) => {
const grid = parseInput(input);
let stepCount = 0;
// Run simulation 1 step at a time until condition is met
while (true) {
stepCount++
runNStepsOfSimultation(grid, 1);
// Condition: all cells are flashing
if (grid.every((row) => row.every(col => col.value === 0))) {
return stepCount;
}
}
}
/**
* UTILITY FUNCTIONS
*/
class Cell {
value: number;
row: number;
col: number;
constructor(v: number, row: number, col: number) {
this.value = v;
this.row = row;
this.col = col;
}
increase() {
this.value += 1;
if (this.value > 9) {
this.value = 0;
}
}
}
export const parseInput = (input: string): Cell[][] => {
return input.trim().split('\n').map((row, rowIdx) => {
return row.split('').map((v, colIdx) => new Cell(Number(v), Number(rowIdx), Number(colIdx)));
})
}
const getNonFlashingCellNaighbours = (cell: Cell, grid: Cell[][]): Cell[] => {
const { row, col } = cell;
const t = grid[row - 1]?.[col];
const tr = grid[row - 1]?.[col + 1];
const r = grid[row]?.[col + 1];
const br = grid[row + 1]?.[col + 1];
const b = grid[row + 1]?.[col];
const bl = grid[row + 1]?.[col - 1];
const l = grid[row]?.[col - 1];
const tl = grid[row - 1]?.[col - 1];
return [t, tr, r, br, b, bl, l, tl].filter(c => !!c && c.value !== 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment