Skip to content

Commit

Permalink
simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
shahata committed Jan 13, 2024
1 parent d90887c commit 85f5ab5
Showing 1 changed file with 28 additions and 35 deletions.
63 changes: 28 additions & 35 deletions src/2023/day24.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,3 @@
function parse(input) {
return input.split('\n').map(line => {
let [point, velocity] = line.split(' @ ');
point = point.split(', ').map(n => +n);
velocity = velocity.split(', ').map(n => +n);
return { point, velocity };
});
}

export function part1(input, min = 2e14, max = 4e14) {
let hails = parse(input);
hails = hails.map(({ point, velocity }) => {
let point2 = point.map((n, i) => n + velocity[i]);
let m = (point[1] - point2[1]) / (point[0] - point2[0]);
let n = point[1] - m * point[0];
return { point, velocity, m, n };
});
let result = 0;
for (let i = 0; i < hails.length; i++) {
for (let j = i + 1; j < hails.length; j++) {
let { m: m1, n: n1 } = hails[i];
let { m: m2, n: n2 } = hails[j];
let x = (n2 - n1) / (m1 - m2);
let y = m1 * x + n1;
if (x > min && x < max && y > min && y < max) {
if ((x - hails[i].point[0]) / hails[i].velocity[0] < 0) continue;
if ((x - hails[j].point[0]) / hails[j].velocity[0] < 0) continue;
result++;
}
}
}
return result;
}

// 1) px0 + vx0 t0 = pxr + vxr t0
// 2) py0 + vy0 t0 = pyr + vyr t0
// 1) t0 = (pxr - px0) / (vx0 - vxr)
Expand Down Expand Up @@ -70,6 +36,34 @@ function cramer(A, B) {
return A.map((_, i) => det(A.map((r, j) => r.toSpliced(i, 1, B[j]))) / detA);
}

// 1) px1 + vx1 t1 = px2 + vx2 t2
// 2) py1 + vy1 t1 = py2 + vy2 t2
// 1) t1 vx1 - t2 vx2 = px2 - px1
// 2) t1 vy1 - t2 vy2 = py2 - py1
export function part1(input, min = 2e14, max = 4e14) {
let hails = input.split('\n').map(line => line.match(/-?\d+/g).map(BigInt));
let result = 0;
for (let i = 0; i < hails.length; i++) {
for (let j = i + 1; j < hails.length; j++) {
const [px1, py1, , vx1, vy1] = hails[i];
const [px2, py2, , vx2, vy2] = hails[j];
const A = [
[vx1, -vx2],
[vy1, -vy2],
];
const B = [px2 - px1, py2 - py1];
if (det(A) === 0n) continue;
const [t1, t2] = cramer(A, B);
const x = px1 + vx1 * t1;
const y = py1 + vy1 * t1;
if (t1 > 0 && t2 > 0 && x > min && x < max && y > min && y < max) {
result++;
}
}
}
return result;
}

export function part2(input) {
const hails = input.split('\n').map(line => line.match(/-?\d+/g).map(BigInt));
const A = [];
Expand All @@ -82,7 +76,6 @@ export function part2(input) {
// import { init } from 'z3-solver';
// export async function part2(input) {
// const hails = parse(input);

// const { Context } = await init();
// const { Solver, Int } = Context('main');
// const solver = new Solver();
Expand Down

0 comments on commit 85f5ab5

Please sign in to comment.