Post date: Jun 04, 2017 12:29:41 PM
"Given an XY coordinate system, how many distinct right triangles can you form where one point is on 0,0 and the other two points are on integer x and y coordinates between 0 and 50 inclusive?"
This problem is a three-fer, where I give three different solutions. We usually prefer set-based logic as SQL developers, so here is the faster, set-based solution.
; WITH Fifty (i) AS
(
SELECT 0
UNION ALL
SELECT i + 1
FROM Fifty
WHERE i < 50
),
Points (x1, y1, x2, y2, rt) AS
(
SELECT x1.i, y1.i, x2.i, y2.i, 0
FROM Fifty x1, Fifty y1, Fifty x2, Fifty y2
WHERE NOT (x1.i = x2.i AND y1.i = y2.i)
AND NOT (x1.i = 0 AND y1.i = 0)
AND NOT (x2.i = 0 AND y2.i = 0)
)
SELECT *
INTO #Points
FROM Points
UPDATE #Points
SET rt = 1
WHERE x1 * x2 + y1 * y2 = 0
UPDATE #Points
SET rt = 1
WHERE rt = 0
AND (0 - x1) * (x2 - x1) + (0 - y1) * (y2 - y1) = 0
UPDATE #Points
SET rt = 1
WHERE rt = 0
AND (x1 - x2) * (0 - x2) + (y1 - y2) * (0 - y2) = 0
SELECT COUNT(*)/2
FROM #Points
WHERE rt = 1
DROP TABLE #Points