Say I have the following 5x5 one-dimensional array. (The white number refers to the index. Ignore the other colors, I'm working on an A* implementation and was using this image as a reference)
And I want to find the Manhattan distance between index 16 and index 9, which would be 5.
Normally Manhatten Distance is done like so:
return Math.abs(a.x - b.x) + Math.abs(a.y - b.y)
But with a one-dimensional array I don't have x (col) and y (row) values. I only have the index. Is the only way to calculate the Manhattan Distance with a 1D array to turn the indexes into x and y values and then calculate it normally like this?
let aX = Math.floor(idx1 % width); let aY = Math.floor(idx1 / width); let bX = Math.floor(idx2 % width); let bY = Math.floor(idx2 / width); return Math.abs(aX - bX) + Math.abs(aY - bY);
Or is there a way to do it without converting the one-dimensional indexes to two dimensions?
https://stackoverflow.com/questions/66616376/how-to-find-manhattan-distance-in-one-dimensional-array March 14, 2021 at 01:19AM
没有评论:
发表评论