jamaik

Untitled

Dec 5th, 2021
543
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { readFileSync } from "fs";
  2. const dataSet = readFileSync(`${__dirname}/inputs/day5.txt`, "utf8").replace(/\r\n/g,'\n').split("\n")
  3.  
  4. let SIZE = 0;
  5. const points = dataSet.map(d => {
  6.     const [a, b] = d.split(" -> ")
  7.         .map(s => {
  8.             const [x, y] = s.split(",")
  9.             return { x: +x, y: +y };
  10.         });
  11.     const size = Math.max(a.x, a.y, b.x, b.y) + 1;
  12.     if (size > SIZE) {
  13.         SIZE = size;
  14.     }
  15.     return [a, b];
  16. });
  17.  
  18. const grid = new Array(SIZE).fill(0).map(() => new Array(SIZE).fill(0));
  19.  
  20. for (const [a, b] of points) {
  21.     const d = (b.y - a.y) / (b.x - a.x);
  22.     if (Math.abs(d) === Infinity) {
  23.         const [start, end] = [a.y, b.y].sort((r, t) => r - t);
  24.         for (let y = start; y <= end; y += 1) {
  25.             grid[y][a.x] += 1;
  26.         }
  27.         continue;
  28.     }
  29.     const [start, end] = [a.x, b.x].sort((r, t) => r - t);
  30.     for (let x = start; x <= end; x += 1) {
  31.         grid[d*(x - a.x) + a.y][x] += 1;
  32.     }
  33. }
  34.  
  35. const sum = grid.flat().reduce((s, x) => x > 1 ? s + 1 : s, 0)
  36. console.log("SUM", sum)
RAW Paste Data