Skip to content

Instantly share code, notes, and snippets.

@tluyben
Created Dec 5, 2021
Embed
What would you like to do?
import { accessSync, promises as fs } from 'fs';
(async()=>{
const input = await fs.readFile("./interpretertests/aoc_21_5_input.txt", 'utf8')
const drawing = (straight) => input.split('\n').reduce((acc, line) => {
let [[x1,y1],[x2,y2]] = line.split(' -> ').map(x => x.split(',').map(x => parseInt(x)))
if (straight && x1!=x2 && y1!=y2) return acc
if (Math.abs(x2-x1) > Math.abs(y2-y1)) {
const yi = (y2-y1)/(x2-x1)
const xi = x1>x2 ? -1 : 1
let i = x1
while (Math.abs(i-x2-xi)>0) {
if (!acc.grid[i]) acc.grid[i] = []
if (acc.grid[i][y1+(i-x1)*yi]) {
acc.grid[i][y1+(i-x1)*yi]++
if (acc.grid[i][y1+(i-x1)*yi]==2) acc.hits++
} else
acc.grid[i][y1+(i-x1)*yi] = 1
i+=xi
}
} else {
const xi = (x2-x1)/(y2-y1)
const yi = y1>y2 ? -1 : 1
let i = y1
while (Math.abs(i-y2-yi)>0) {
if (!acc.grid[x1+(i-y1)*xi]) acc.grid[x1+(i-y1)*xi] = []
if (acc.grid[x1+(i-y1)*xi][i]) {
acc.grid[x1+(i-y1)*xi][i]++
if (acc.grid[x1+(i-y1)*xi][i]==2) acc.hits++
} else
acc.grid[x1+(i-y1)*xi][i] = 1
i+=yi
}
}
return acc
}, {grid:[], hits: 0})
//console.table(drawing2.grid)
console.log(drawing(true).hits)
console.log(drawing(false).hits)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment