Post date: Jun 04, 2017 12:27:40 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. The cleanest way for me to do this is with a function. It may not be the fastest, because we are doing single calculations aat a time (up to 5 per row). This takes 30 seconds which is not bad. But I can do better (see next post).
CREATE FUNCTION dbo.IsRightTriangle(@x1 int, @y1 int, @x2 int, @y2 int)
RETURNS bit
AS
BEGIN
-- A triangle is a right triangle if it contains a right angle.
-- The angle between two sides (vectors in a coordinate plane) is right if their scalar product is equal ot zero.
-- We have no clues about which of the three angle is meant to be the right angle so we need to check all three.
DECLARE @vx1 int, @vy1 int, @vx2 int, @vy2 int
-- Angle 1: At (0, 0)
IF @x1 * @x2 + @y1 * @y2 = 0
RETURN 1
-- Angle 2: At point 1
SELECT @vx1 = 0 - @x1, @vy1 = 0 - @y1, @vx2 = @x2 - @x1, @vy2 = @y2 - @y1
IF @vx1 * @vx2 + @vy1 * @vy2 = 0
RETURN 1
SELECT @vx1 = @x1 - @x2, @vy1 = @y1 - @y2, @vx2 = 0 - @x2, @vy2 = 0 - @y2
IF @vx1 * @vx2 + @vy1 * @vy2 = 0
RETURN 1
RETURN 0
END
GO
; WITH Fifty (i) AS
(
SELECT 0
UNION ALL
SELECT i + 1
FROM Fifty
WHERE i < 50
),
Points (x1, y1, x2, y2) AS
(
SELECT x1.i, y1.i, x2.i, y2.i
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)
)
-- The Points CTE above returns triangles and their mirror images. Both are right triangles but should be counted once.
SELECT COUNT(*)/2
FROM Points
WHERE dbo.IsRightTriangle(x1, y1, x2, y2) = 1
DROP FUNCTION dbo.IsRightTriangle
GO