This is a problem which has tripped me up for some time. Given an $(n\times m)$ grid, one has the possibility to choose all possible permutations of three points, and this would then give all possible triangles within that grid, eg: for a $(5\times 5)$ grid:
(* Mathematica code *)
grid = Flatten[Table[{i,j},{i,5},{j,5}],1];
triangles = Permutations[grid,{3}];
This gives 13769 possible combinations. Now if I were looking at a $(1000\times 1000)$ grid, things would get excessively large. So instead, I want to figure out a quick way to generate triangles - defined by coordinates $((x_1,y_1),(x_2,y_2),(x_3,y_3))$ - which belong to an equivalence class. This equivalence class is defined by the length of each side $(r^2_{12},r^2_{13},r^2_{23})$. For example:
The points $((1,1),(3,4),(2,5))$ belong to the equivalence class $(2,25,29)$. Naturally we could rotate this triangle and it would technically form a new set of points, thus a new triangle, but still belong to the same equivalence class. Furthermore, the points $((1,1),(4,3),(2,5))$ form a totally different triangle. Yet, still belong to that equivalence class. My problem can thus be broken down into two parts:
- Find all possible and unique set of equivalence classes within a given grid.
- Generate three coordinate points (within the boundary of a grid or array) which form a triangle belonging to that particular equivalence class.
- Bonus would be to find ALL possible unique triangle instances which belong to that equivalence class, but for now it would not be necessary.
A preliminary solution for the first problem would be to list the square of all possible lengths on a 2D lattice $(1,2,4,5,8,9,13,16,17,...)$ - which I have my own code to do so, and then find all the unique 3-tupples of this list. Going this route brings two problems:
- Not all tupples within this list give a valid equivalence class of a triangle on a lattice - e.g $(1,2,4)$
- I would need another bit of code to test whether such an equivalence class generates a valid triangle.
Thus far, I have settled with generating random triangles and binning them in whatever equivalence class they happen to form. Unfortunately, although relatively quick, it is not uniform enough, and it destroys my memory. For my purposes I need some fine structure, this relates to generating an even spread of triangles across all possible equivalence classes within the grid.
NB since I am dealing with really large grids, speed here is extremely important.
Lastly, I appreciate the fact that sometimes no matter how quick some code my be, due to the sheer size of certain operations it will always take time.
