Skip to content

Commit 5150909

Browse files
added GridGetX and GridGetY (TheAlgorithms#222)
* added GridGetX and GridGetY * fixed Node CI issues * fixed Node CI issues * made requested changes * fixed Node CI errors
1 parent 40000d5 commit 5150909

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

Maths/GridGet.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
author: TangibleDream
3+
license: GPL-3.0 or later
4+
5+
These methods will find x or y given the element and columns for a 2 dimensional array.
6+
7+
If your array is a perfect square, you can find columns by getting the square
8+
root of the length of the array.
9+
10+
Let's say for instance you had an array of 10 by 10 or 100, elements and you wanted to
11+
find the shortest distance between element 3, and element 49. In this case coding out
12+
a function to return the distance without finding x and y for both elements I found to
13+
be painful. If you first find x and y, where 3 becomes 4,1 and 49 becomes 10,5, you can
14+
find distance by first subtracting x from x and y from y this returns 6,4 or -6,-4.
15+
Next apply absolute value to assure the results are positive,
16+
last choose the maximum value of the set, or 6.
17+
18+
+--+--+--+--+--+--+--+--+--+--+
19+
| | | | 3| | | | | | |
20+
+--+--+--+--+--+--+--+--+--+--+
21+
| | | | | | | | | | |
22+
+--+--+--+--+--+--+--+--+--+--+
23+
| | | | | | | | | | |
24+
+--+--+--+--+--+--+--+--+--+--+
25+
| | | | | | | | | |49|
26+
+--+--+--+--+--+--+--+--+--+--+
27+
| | | | | | | | | | |
28+
29+
+--+--+--+--+--+--+--+--+--+--+
30+
| | | | 3| | | | | | |
31+
+--+--+--+--+--+--+--+--+--+--+
32+
| | | | | 1| | | | | |
33+
+--+--+--+--+--+--+--+--+--+--+
34+
| | | | | | 2| | | | |
35+
+--+--+--+--+--+--+--+--+--+--+
36+
| | | | | | | 3| 4| 5|6!|
37+
+--+--+--+--+--+--+--+--+--+--+
38+
| | | | | | | | | | |
39+
40+
*/
41+
42+
const gridGetX = (columns, index) => {
43+
while ((index + 1) > columns) {
44+
index = index - columns
45+
}
46+
return (index + 1)
47+
}
48+
49+
const gridGetY = (columns, index) => {
50+
return (Math.floor(index / columns)) + 1
51+
}
52+
53+
console.log(`If a square array has 400 elements, then the value of x for the 27th element is ${gridGetX(Math.sqrt(400), 27)}`)
54+
console.log(`If an array has 7 columns and 3 rows, then the value of x for the 11th element is ${gridGetX(7, 11)}`)
55+
console.log(`If a square array has 400 elements, then the value of y for the 27th element is ${gridGetY(Math.sqrt(400), 27)}`)
56+
console.log(`If an array has 7 columns and 3 rows, then the value of y for the 11th element is ${gridGetY(7, 11)}`)

0 commit comments

Comments
 (0)