Post date: Jun 04, 2017 12:32:20 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.I felt that I needed to develop a way to weed out the mirror image records. So I came up with this. It isn't as clean as I would have hoped, but it's not bad.
; 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
; WITH Mirrored (x1, y1, x2, y2, rn1, rn2) AS
(
SELECT x1, y1, x2, y2
, ROW_NUMBER() OVER (ORDER BY x1, y1, x2, y2)
, ROW_NUMBER() OVER (ORDER BY x2, y2, x1, y1)
FROM #Points
WHERE rt = 1
), Mirrored2 (x1, y1, x2, y2, rn) AS
(
SELECT x1, y1, x2, y2
, ROW_NUMBER() OVER (PARTITION BY CASE WHEN rn1 < rn2 THEN rn1 ELSE rn2 END ORDER BY x1, y1, x2, y2)
FROM Mirrored
)
SELECT COUNT(*)
FROM Mirrored2
WHERE rn = 1
DROP TABLE #Points