|
1 | 1 | const fs = require('fs');
|
2 | 2 | const path = require('path');
|
| 3 | +const distance = require('manhattan'); |
| 4 | +const flat = require('array.prototype.flat'); |
3 | 5 |
|
4 | 6 | let raw_input = fs.readFileSync(path.resolve(__dirname, './input.txt'), 'utf8');
|
5 | 7 |
|
6 | 8 | // Last filter is to remove any empty lines
|
7 |
| -let input = raw_input.split('\n').filter(n => n)[0]; |
| 9 | +let input = raw_input.split('\n').filter(n => n); |
| 10 | + |
| 11 | +let coordinates = input.map(p => p.split(',').map(n => +n)); |
| 12 | + |
| 13 | +let flattened = flat(coordinates); |
| 14 | +let largest = Math.max.apply(null, flattened); |
| 15 | + |
| 16 | +let grid = Array(largest + 2) |
| 17 | + .fill() |
| 18 | + .map(n => { |
| 19 | + return Array(largest + 2).fill(-1); |
| 20 | + }); |
| 21 | + |
| 22 | +// Loop through grid and mark spots that are coordinates |
| 23 | +coordinates.forEach((coord, index) => { |
| 24 | + let [i, j] = coord; |
| 25 | + grid[i][j] = 'C' + index; |
| 26 | +}); |
| 27 | + |
| 28 | +const MIN_DIST = 10000; |
| 29 | + |
| 30 | +let min_dist_count = 0; |
| 31 | +for (let i = 0; i < grid.length; i++) { |
| 32 | + let row = grid[i]; |
| 33 | + for (let j = 0; j < grid.length; j++) { |
| 34 | + let cell = row[j]; |
| 35 | + if (typeof cell !== 'string') { |
| 36 | + // Not a coord, measure it |
| 37 | + let lengths = coordinates.map((coord, index) => { |
| 38 | + return distance(coord, [i, j]); |
| 39 | + }); |
| 40 | + |
| 41 | + let sum = lengths.reduce((a, b) => a + b); |
| 42 | + if (sum < MIN_DIST) { |
| 43 | + grid[i][j] = 'close'; |
| 44 | + min_dist_count++; |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +// Loop through coords, and find ones that are surrounded by "found" areas |
| 51 | +coordinates.forEach(coord => { |
| 52 | + let [i, j] = coord; |
| 53 | + let t = grid[i - 1][j]; |
| 54 | + let r = grid[i][j + 1]; |
| 55 | + let b = grid[i + 1][j]; |
| 56 | + let l = grid[i][j - 1]; |
| 57 | + |
| 58 | + const C = 'close'; |
| 59 | + |
| 60 | + if (t === C && r === C && b === C && l === C) { |
| 61 | + min_dist_count++; |
| 62 | + } |
| 63 | +}); |
| 64 | + |
| 65 | +console.log(min_dist_count); |
0 commit comments