Check if coordinates are adjacent


/ Published in: JavaScript
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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. }

URL: http://books.google.be/books?ei=4RJ8T-ybE8ahOrTR7LwM&id=43qowOBC1CEC&q=manhattan#v=snippet&q=manhattan

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.