Skip to content

Instantly share code, notes, and snippets.

@tluyben
Created December 5, 2021 10:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tluyben/cd66ff6605f14b461833e9c54413aea1 to your computer and use it in GitHub Desktop.
Save tluyben/cd66ff6605f14b461833e9c54413aea1 to your computer and use it in GitHub Desktop.
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