Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Points on a Lattice

I got this question on a coding interview.

Hanna moves in a lattice where every point can be represented by a pair of integers. She moves from point A to point B and then takes a turn 90 degrees right and starts moving till she reaches the first point on the lattice. Find what's the point she would reach? In essence the problem boils down to finding the first point where the perpendicular to a line will intersect. Can someone provide pseudo-code or code snippets as to how I can solve this?

like image 705
Melissa Stewart Avatar asked Dec 09 '25 09:12

Melissa Stewart


2 Answers

I'm assuming you mean that she moves in a straight line from A to B and then turns 90 degrees, and that the lattice is a Cartesian grid with the y axis pointing up and the x axis pointing right.

Let (dx,dy) = (Bx,By)-(Ax,Ay), the vector from point A to point B.

We can rotate this by 90 degrees to give (dy,-dx).

After hanna turns right at B, she will head out along that rotated vector toward (Bx+dy,By-dx)

Since she is moving in a straight line, her vector from B will follow (t.dy,-t.dx), and will hit another lattice point when both of those components are integers, i.e...

She will hit another lattice point at: (Bx + dy/GCD(|dx|,|dy|), By - dx/GCD(|dx|,|dy|) )

like image 75
Matt Timmermans Avatar answered Dec 11 '25 14:12

Matt Timmermans


const findNext = (Ax, Ay, Bx, By) => {
  // Move A to Origin
  const Cx = Bx - Ax;
  const Cy = By - Ay;
  // Rotate by 90 degree clockwise
  const Rx = Cy;
  const Ry = -Cx;
  // Normalize
  const norm = gcd(Math.abs(Rx), Math.abs(Ry));
  const Nx = Rx / norm;
  const Ny = Ry / norm;
  return [Bx + Nx, By + Ny];
};

Here is gcd,

var gcd = function(a, b) {
  if (!b) {
    return a;
  }

  return gcd(b, a % b);
}

Output:

cons result = findNext(1,1,2,2);
console.log(result);
// [3, 1]
like image 23
Salmanul Faris K Avatar answered Dec 11 '25 13:12

Salmanul Faris K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!