In the last month I came across a few posts in facebook asking to count different triangles in a bigger triangle like this one.
After a few attempts counting on screen while pointing with my finger on the display or drawing the triangles on paper and trying to highlight the ones I’ve already counted I realised that it takes me way too long and is kind of boring. Thinking about it a bit I decided try and solve it with a small ruby programm.
My basic idea was to model the triangle puzzle as a set of lines and intersection points. By detecting common intersection points for each set of three lines I then can see if they form a triangle or not.
There are points and lines and puzzles. Lines can have many points. A puzzle has multiple lines. The Puzzle class also handles all the calculations.
- Divide the puzzle into line triples
- Check if line triple makes a trianlge
- Count total triangles
Point and Line classes describe the basic structures. The whole magic then happens in the Puzzle class.
For now I will concentrate on writing tests and making small refactorings to the code base.
I’m wondering how would you approach such problem…