Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const utils = require('../../utils')
- const data = utils.byLine('./input.txt').map(intsS)
- const USE = 10
- const MIN = 200000000000000
- const MAX = 400000000000000
- const SUB = data.slice(0, USE)
- function findLineLambda(a, b, c, d, p, q, r, s) {
- const det = (c - a) * (s - q) - (r - p) * (d - b);
- if (det === 0) return null
- return Math.round(((s - q) * (r - a) + (p - r) * (s - b)) / det)
- }
- function findIntersectionPoint(a, b, d1 = 0, d2 = 1) {
- let lambda = findLineLambda(
- a[d1], a[d2], a[d1] + a[d1 + 3], a[d2] + a[d2 + 3],
- b[d1], b[d2], b[d1] + b[d1 + 3], b[d2] + b[d2 + 3],
- )
- if (lambda === null) return null
- let f = a[d1] + lambda * a[d1 + 3]
- let g = a[d2] + lambda * a[d2 + 3]
- return [f, g]
- }
- function findCommonIntersection(v, d1 = 0, d2 = 1) {
- let viable = true
- let current
- const transformed = SUB.map(line => {
- const copy = [...line]
- copy[d1 + 3] += v[0]
- copy[d2 + 3] += v[1]
- return copy
- })
- utils.pairs(transformed, (a, b) => {
- if (!viable) return false
- const point = findIntersectionPoint(a, b, d1, d2)
- if (point === null) return
- if (!current) current = point
- viable = point[0] === current[0] && point[1] === current[1]
- })
- if (!viable) return false
- return current
- }
- let intersections = 0
- utils.pairs(data, (a, b) => {
- let p = findIntersectionPoint(a, b)
- if (!p) return
- let [x, y] = findIntersectionPoint(a, b, 0, 1)
- if (x < MIN || x > MAX || y < MIN || y > MAX) return // out of bounds
- if ((x < a[0] && a[3] > 0) || (x > a[0] && a[3] < 0)) return // in the past for A
- if ((x < b[0] && b[3] > 0) || (x > b[0] && b[3] < 0)) return // in the past for B
- intersections++
- })
- function solve() {
- for (let x = 0; x <= Infinity; x++) {
- for (let y = 0; y <= x; y++) {
- for (let [sx, sy] of [[1, 1], [1, -1], [-1, 1], [-1, -1]]) {
- // X and Y have an intersection
- let xy = findCommonIntersection([x * sx, y * sy], 0, 1)
- if (!xy) continue
- for (let z = 0; z <= Infinity; z++) {
- for (let sz of [1, -1]) {
- // find intersection for X and Z, if it exists, it's the result
- let xz = findCommonIntersection([x * sx, z * sz], 0, 2)
- if (!xz) continue
- return xy[0] + xy[1] + xz[1]
- }
- }
- }
- }
- }
- }
- console.log('Part 1', intersections)
- console.log('Part 2', solve())
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement