Skip to content

added GridGetX and GridGetY #222

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 7, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Maths/GridGet.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
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) => {
while ((index + 1) > columns) {
index = index - columns
}
return (index + 1)
}

const gridGetY = (columns, index) => {
return (Math.floor(index / columns)) + 1
}

console.log(`If a square array has 400 elements, then the value of x for the 27th element is ${gridGetX(Math.sqrt(400), 27)}`)
console.log(`If an array has 7 columns and 3 rows, then the value of x for the 11th element is ${gridGetX(7, 11)}`)
console.log(`If a square array has 400 elements, then the value of y for the 27th element is ${gridGetY(Math.sqrt(400), 27)}`)
console.log(`If an array has 7 columns and 3 rows, then the value of y for the 11th element is ${gridGetY(7, 11)}`)