diff --git a/11/code.js b/11/code.js new file mode 100644 index 0000000..f2dd2f9 --- /dev/null +++ b/11/code.js @@ -0,0 +1,72 @@ +const fs = require('fs'); +const inputArray = fs.readFileSync('input.txt').toString().split("\n"); + +const octopi = []; +for (const line of inputArray) { + octopi.push(line.split("").map(Number)); +} + +const height = octopi.length; +const width = octopi[0].length; + +// Part One +// const runs = 100; + +// Part Two +const runs = 1000; + +let flashes = 0; + +function flash(flashed) { + let flashing = 0; + for (let h = 0; h < height; h++) { + for (let w = 0; w < width; w++) { + const coords = `${h}-${w}`; + if (!flashed.includes(coords) && octopi[h][w] > 9) { + flashes++; + flashing++; + flashed.push(coords); + if (h >= 1) { + if (w >= 1) octopi[h-1][w-1]++; + octopi[h-1][w]++; + if (w < width - 1) octopi[h-1][w+1]++; + } + if (w >= 1) octopi[h][w-1]++; + if (w < width - 1) octopi[h][w+1]++; + if (h < height - 1) { + if (w >= 1) octopi[h+1][w-1]++; + octopi[h+1][w]++; + if (w < width - 1) octopi[h+1][w+1]++; + } + + } + } + } + if (flashing === 0) return; + flash(flashed); + return; +} + +for (let r = 1; r <= runs; r++) { + const flashed = []; + for (let h = 0; h < height; h++) { + for (let w = 0; w < width; w++) { + octopi[h][w]++; + } + } + flash(flashed); + for (let h = 0; h < height; h++) { + for (let w = 0; w < width; w++) { + if (octopi[h][w] > 9) { + octopi[h][w] = 0; + } + } + } + + if (octopi.flat().reduce((a, b) => parseInt(a) + parseInt(b), 0) === 0) { + console.log(`Synchronized on run ${r}`); + break; + } +} + +console.log(`Total flashes: ${flashes}`); \ No newline at end of file diff --git a/11/input.txt b/11/input.txt new file mode 100644 index 0000000..07c27d2 --- /dev/null +++ b/11/input.txt @@ -0,0 +1,10 @@ +4743378318 +4664212844 +2535667884 +3273363861 +2282432612 +2166612134 +3776334513 +8123852583 +8181786685 +4362533174 \ No newline at end of file diff --git a/11/sample.txt b/11/sample.txt new file mode 100644 index 0000000..a3819c9 --- /dev/null +++ b/11/sample.txt @@ -0,0 +1,10 @@ +5483143223 +2745854711 +5264556173 +6141336146 +6357385478 +4167524645 +2176841721 +6882881134 +4846848554 +5283751526 \ No newline at end of file