Posted By

hellowouter on 04/04/12


distance coordinates Manhattan coords isAdjacent taxicab

Versions (?)

Check if coordinates are adjacent

 / Published in: JavaScript


This function returns true if the two sets of coordinates are neighbors and false if they ar not. The function easily determines whether they are neighbors by looking at the distance between the positions along both axes, also callled the Manhattan distance. The sum of the two distances must be exactly 1 if the positions are adjacent.

Note: the coordinates should be integers

  1. // returns true if (x1,y1) is adjacent to (x2,y2)
  2. function isAjdacent(x1, y1, x2, y2) {
  3. var dx = Math.abs(x1 - x2),
  4. dy = Math.abs(y1 - y2);
  5. return (dx + dy === 1);
  6. }

Report this snippet  

You need to login to post a comment.