2020-07-06 21:10:57 -05:00
|
|
|
/*
|
|
|
|
|
author: TangibleDream
|
|
|
|
|
license: GPL-3.0 or later
|
|
|
|
|
|
|
|
|
|
These methods will find x or y given the element and columns for a 2 dimensional array.
|
|
|
|
|
|
|
|
|
|
If your array is a perfect square, you can find columns by getting the square
|
|
|
|
|
root of the length of the array.
|
|
|
|
|
|
|
|
|
|
Let's say for instance you had an array of 10 by 10 or 100, elements and you wanted to
|
|
|
|
|
find the shortest distance between element 3, and element 49. In this case coding out
|
|
|
|
|
a function to return the distance without finding x and y for both elements I found to
|
|
|
|
|
be painful. If you first find x and y, where 3 becomes 4,1 and 49 becomes 10,5, you can
|
|
|
|
|
find distance by first subtracting x from x and y from y this returns 6,4 or -6,-4.
|
|
|
|
|
Next apply absolute value to assure the results are positive,
|
|
|
|
|
last choose the maximum value of the set, or 6.
|
|
|
|
|
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | 3| | | | | | |
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | | | | | | | |
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | | | | | | | |
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | | | | | | |49|
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | | | | | | | |
|
|
|
|
|
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | 3| | | | | | |
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | | 1| | | | | |
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | | | 2| | | | |
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | | | | 3| 4| 5|6!|
|
|
|
|
|
+--+--+--+--+--+--+--+--+--+--+
|
|
|
|
|
| | | | | | | | | | |
|
|
|
|
|
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
const gridGetX = (columns, index) => {
|
2020-10-11 19:47:49 +00:00
|
|
|
while (index + 1 > columns) {
|
2020-07-06 21:10:57 -05:00
|
|
|
index = index - columns
|
|
|
|
|
}
|
2020-10-11 19:47:49 +00:00
|
|
|
return index + 1
|
2020-07-06 21:10:57 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const gridGetY = (columns, index) => {
|
2020-10-11 19:47:49 +00:00
|
|
|
return Math.floor(index / columns) + 1
|
2020-07-06 21:10:57 -05:00
|
|
|
}
|
|
|
|
|
|
2020-10-11 19:47:49 +00:00
|
|
|
export { gridGetX, gridGetY }
|