How can I improve my sorting?

A function receives 3 positions that make up a triangle and must find the 2 positions that make up the longest side.

image

My implementation feels hacky, and I suspect there is a better way to do this. How might I improve this?

local sideLengths = {
 -- {point on side, other point on side, third point, side length}
	{p0, p1, p2, (p0.Position - p1.Position).magnitude},
	{p1, p2, p0, (p1.Position - p2.Position).magnitude},
	{p2, p0, p1, (p2.Position - p0.Position).magnitude}
}

table.sort(sideLengths, function(a, b) -- Sorts sideLengths in descending order by side length
	return a[4] > b[4]
end)

local a = sideLengths[1][1].Position
local b = sideLengths[1][2].Position
local c = sideLengths[1][3].Position

I don’t see any geometric shortcut that avoids needing to calculate the three side lengths, so that’s the obvious first step. If all you want is the two points that make up the longest side then it only takes a couple of conditional statements.

local length01 = (p0.Position - p1.Position).magnitude
local length02 = (p0.Position - p2.Position).magnitude
local length12 = (p1.Position - p2.Position).magnitude

local a, b, length = p0, p1, length01
if length02 > length then
	a, b, length = p0, p2, length02
end
if length12 > length then
	a, b, length = p1, p2, length12
end
2 Likes