The Challenge
Given two vertexes and a point calculate the distance to the line segment defined by those points.
This can be calculated with the following psudocode
def dist(point, v1, v2):
direction := normalize(v2-v1)
distance := length(v2-v1)
difference := point - v1
pointProgress := dot(difference, direction)
if (pointProgress <= 0):
return magnitude(point - v1)
else if (pointProgress >= distance):
return magnitude(point - v2)
else
normal := normalize(difference - (direction * pointProgress))
return dot(difference, normal)
Answers may support either 2 dimensions, or 3, and may optionally support any number of higher or lower dimensions.
As it does not substantially change the difficulty of the challenge, answers need only be accurate to the whole number, and I/O can be assumed to fit within the [0,127] range. This is to allow more languages to focus only on the challenge spec, rather than implementing floating points.
Test Cases
1: point=[005,005], v1=[000,000] v2=[010,000] :: distance=005.00 # Horizontal
2: point=[005,005], v1=[010,000] v2=[010,010] :: distance=005.00 # Vertical
3: point=[000,010], v1=[000,000] v2=[010,010] :: distance=007.07 # Diagonal
4: point=[010,000], v1=[000,000] v2=[010,010] :: distance=007.07 # Diagonal, Clockwise
5: point=[000,000], v1=[002,002] v2=[004,008] :: distance=002.83 # Not near the normal
6: point=[000,002], v1=[002,002] v2=[002,002] :: distance=002.00 # Zero length segment
Rules
- Standard IO Applies
- Standard Loopholes Apply
- This is code-golf so fewest bytes wins!
- Have Fun!
√8
\$\endgroup\$