Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Forum Search
Forum Statistics
UsersTotal Post History
- Posts:
- 78574
- Topics:
- 17965
7-Day Post History
- New Posts:
- 72
- New Topics:
- 37
- Active Topics:
- 39
Our newest member
Other
-
FAQ
All times are UTC [ DST ]
Google Ads
Puzzle 23 - Distance to line segment
Forum rules
Always post answers in a "Hidecode" tag, so that others have a chance to answer the question too.
Always post answers in a "Hidecode" tag, so that others have a chance to answer the question too.
26 posts • Page 1 of 2 • 1, 2
Please wait...
Puzzle 23 - Distance to line segment
Calculate the shortest distance from a point to a line segment.


Given the coordinates of the line segment (shown in blue), calculate the shortest distance to a given point (also shown in blue). The distance that you are to calculate is represented by the red line. If the point is 'outside' the line segment, meaning, you cannot draw a perpendicular line to it, then you should return the distance from the given point to the closest end point (shown in the second image).
The calculations are relatively simple. No points will be rewarded for incorrect distances (within reasonable rounding issues). Max points will be awarded for correct results and fast performance.


Given the coordinates of the line segment (shown in blue), calculate the shortest distance to a given point (also shown in blue). The distance that you are to calculate is represented by the red line. If the point is 'outside' the line segment, meaning, you cannot draw a perpendicular line to it, then you should return the distance from the given point to the closest end point (shown in the second image).
The calculations are relatively simple. No points will be rewarded for incorrect distances (within reasonable rounding issues). Max points will be awarded for correct results and fast performance.
-George
-

gmmastros - LTD Admin

-











- Posts: 2222
- Joined: Tue Oct 09, 2007 5:19 pm
Re: Puzzle 23 - Distance to line segment
Here's mine. I'm bad at math, so I didn't use any of those scary geometry things, except for a distance formula. I'd love to have implemented this without sqrt or exponentiation, but I'm not sure how.
Code is hidden, SHOW
- ChibaPet
- Apprentice

-
- Posts: 5
- Joined: Fri Feb 20, 2009 10:47 pm
Re: Puzzle 23 - Distance to line segment
ChibaPet wrote:Here's mine. I'm bad at math, so I didn't use any of those scary geometry things, except for a distance formula. I'd love to have implemented this without sqrt or exponentiation, but I'm not sure how.
Hm, yeah, my solution fails if the points defining the line segment are listed in the reverse order. I'm not going to bother fixing it, but I should figure out which of a and b is closest to the origin, and have that determine which endpoint is checked against "<" and which is checked against ">". I also feel like there are common cases I'm missing, but maybe that would suffice.
Alright, I'll do it, or it's going to gnaw at me.
Code is hidden, SHOW
There. Now the order of points in the line segment doesn't matter, at the expense of two more distance calculations per problem.
- ChibaPet
- Apprentice

-
- Posts: 5
- Joined: Fri Feb 20, 2009 10:47 pm
Re: Puzzle 23 - Distance to line segment
Nice work ChibaPet, and Welcome 
I can't test it, but it looks about like what I had in mind (which is probably bad news for you!)

I can't test it, but it looks about like what I had in mind (which is probably bad news for you!)
Say what you like about the tenets of National Socialism Dude, at least it's an ethos
-

AlexCuse - LTD Admin

-










- Posts: 5264
- Joined: Tue Oct 09, 2007 5:26 pm
- Location: Pennsylvania, US
Re: Puzzle 23 - Distance to line segment
I followed a link here from reddit and figured I'd give it a go. Here's my solution in C.
Code is hidden, SHOW
-

koorogi - Newbie

-
- Posts: 1
- Joined: Sat Feb 21, 2009 12:29 am
Re: Puzzle 23 - Distance to line segment
ChibaPet wrote:Here's mine. I'm bad at math, so I didn't use any of those scary geometry things, except for a distance formula. I'd love to have implemented this without sqrt or exponentiation, but I'm not sure how.
Sorry to sound stupid but what language is that you are using.
pink fuzzy slippers
-

chrissie1 - Senior Guru

-











- Posts: 9107
- Joined: Wed Oct 10, 2007 7:18 pm
- Location: Belgium
Re: Puzzle 23 - Distance to line segment
chrissie1 wrote:ChibaPet wrote:Here's mine. I'm bad at math, so I didn't use any of those scary geometry things, except for a distance formula. I'd love to have implemented this without sqrt or exponentiation, but I'm not sure how.
Sorry to sound stupid but what language is that you are using.
ummm... I think my sarcasm filter is a bit wonky... are you serious? (I really can't tell for some reason
)...or didn't you read the first line?
a smile is worth a thousand kind words, so smile, it's easy! 
CODE: $5
WORKING CODE: $500
PROPERLY DESIGNED & WORKING CODE: Priceless

CODE: $5
WORKING CODE: $500
PROPERLY DESIGNED & WORKING CODE: Priceless
-

damber - LTD Admin

-









- Posts: 3117
- Joined: Tue Oct 09, 2007 1:48 pm
- Location: North Wales, UK
Re: Puzzle 23 - Distance to line segment
damber wrote:chrissie1 wrote:ChibaPet wrote:Here's mine. I'm bad at math, so I didn't use any of those scary geometry things, except for a distance formula. I'd love to have implemented this without sqrt or exponentiation, but I'm not sure how.
Sorry to sound stupid but what language is that you are using.
ummm... I think my sarcasm filter is a bit wonky... are you serious? (I really can't tell for some reason)
...or didn't you read the first line?
ah math is the language. Didn't know that was a programming language. Or am I misstaken.
My limited English tell me math is short fo mathematics.
ah now I see it's perl.
Nope I missed that one.
I changed the hidecode tags to reflect that for other people like me.
pink fuzzy slippers
-

chrissie1 - Senior Guru

-











- Posts: 9107
- Joined: Wed Oct 10, 2007 7:18 pm
- Location: Belgium
Re: Puzzle 23 - Distance to line segment
I've created an executable to perform this calculation and also to show the task graphically. This should run on any windows 2000+ operating system.
http://tinyurl.com/b66rfr
http://tinyurl.com/b66rfr
-George
-

gmmastros - LTD Admin

-











- Posts: 2222
- Joined: Tue Oct 09, 2007 5:19 pm
Re: Puzzle 23 - Distance to line segment
Chrissie, hopefully there aren't too many people like you 
This was much trickier than I expected, but I learned a lot! Cut out some stuff in the LineSegment class (I hope to eventually make this able to determine the intersection point and create the intersecting line as well - perhaps this could be a puzzle for another week?) hopefully didn't break anything

This was much trickier than I expected, but I learned a lot! Cut out some stuff in the LineSegment class (I hope to eventually make this able to determine the intersection point and create the intersecting line as well - perhaps this could be a puzzle for another week?) hopefully didn't break anything
Code is hidden, SHOW
Say what you like about the tenets of National Socialism Dude, at least it's an ethos
-

AlexCuse - LTD Admin

-










- Posts: 5264
- Joined: Tue Oct 09, 2007 5:26 pm
- Location: Pennsylvania, US
Re: Puzzle 23 - Distance to line segment
I'm trying to test the code submitted.
So far, I've only tested koorogi's code. His code produces the correct answer and is only slightly slower than my own code, which I will post later.
When I compile my code, it runs in 160 nano-seconds. Koorogi's code (converted to VB, sorry) runs in 300 nano-seconds.
Please, can everyone test their own performance. Run the code a couple million times and post the execution time (divided by the number of loops of course).
So far, I've only tested koorogi's code. His code produces the correct answer and is only slightly slower than my own code, which I will post later.
When I compile my code, it runs in 160 nano-seconds. Koorogi's code (converted to VB, sorry) runs in 300 nano-seconds.
Please, can everyone test their own performance. Run the code a couple million times and post the execution time (divided by the number of loops of course).
-George
-

gmmastros - LTD Admin

-











- Posts: 2222
- Joined: Tue Oct 09, 2007 5:19 pm
Re: Puzzle 23 - Distance to line segment
A tick is supposedly one hundred nanoseconds, I'm sure its' a bit more than that though. I'm too lazy to do anything more complicated.
These times are on a pretty slow laptop, with a lot of other stuff running.
[hide]Lets define the points - P1 and P2 will define the line segment, P3 will be the
point to get distance from...
P1 x:
100
P1 y:
100
P2 x:
200
P2 y:
200
P3 x:
350
P3 y:
795
Distance is: 613.616329639295
Duration is: 2590000 Ticks or 1.295 Ticks per execution
Would you like to try again? (Y/N)[/hide]
These times are on a pretty slow laptop, with a lot of other stuff running.
[hide]Lets define the points - P1 and P2 will define the line segment, P3 will be the
point to get distance from...
P1 x:
100
P1 y:
100
P2 x:
200
P2 y:
200
P3 x:
350
P3 y:
795
Distance is: 613.616329639295
Duration is: 2590000 Ticks or 1.295 Ticks per execution
Would you like to try again? (Y/N)[/hide]
Say what you like about the tenets of National Socialism Dude, at least it's an ethos
-

AlexCuse - LTD Admin

-










- Posts: 5264
- Joined: Tue Oct 09, 2007 5:26 pm
- Location: Pennsylvania, US
Re: Puzzle 23 - Distance to line segment
Chibapet,
The code you posted works if the line is not horizontal or vertical.
The code you posted works if the line is not horizontal or vertical.
-George
-

gmmastros - LTD Admin

-











- Posts: 2222
- Joined: Tue Oct 09, 2007 5:19 pm
Re: Puzzle 23 - Distance to line segment
gmmastros wrote:Chibapet,
The code you posted works if the line is not horizontal or vertical.
Yar. Broken.
The following corrects that. It could search for point C being on the line which contains the line segment, but I guess that would only be worthwhile if it's a common case in the data.
Anyway, it's less pretty now, but more correct. Lucky I don't program spacecraft controls, I guess.
Code is hidden, SHOW
- ChibaPet
- Apprentice

-
- Posts: 5
- Joined: Fri Feb 20, 2009 10:47 pm
Re: Puzzle 23 - Distance to line segment
Here is my algorithm:
My code has many similarities to code already posted. The main difference is... I calculate the point where the 'distance' line intersects the line segment. This could be anywhere on the line or at one of the end points. From there... it's a simple distance calculation.
Code is hidden, SHOW
My code has many similarities to code already posted. The main difference is... I calculate the point where the 'distance' line intersects the line segment. This could be anywhere on the line or at one of the end points. From there... it's a simple distance calculation.
-George
-

gmmastros - LTD Admin

-











- Posts: 2222
- Joined: Tue Oct 09, 2007 5:19 pm
Re: Puzzle 23 - Distance to line segment
By the way.... I'd love to see someone post a javascript version. Anyone?
-George
-

gmmastros - LTD Admin

-











- Posts: 2222
- Joined: Tue Oct 09, 2007 5:19 pm
Re: Puzzle 23 - Distance to line segment
gmmastros wrote:Here is my algorithm:
Hm, I'm not understanding what you're doing with the slope... Math is not my strong point. But does that work? Comments in the code would be a welcome addition!
Also, near the end, I think you want the square root in your distance calculation... Is Sqr the square root in VB? A quick Google doesn't enlighten me overmuch about a VB built-in square root function, but the principle of least surprise says "Sqr" squares its argument.
- ChibaPet
- Apprentice

-
- Posts: 5
- Joined: Fri Feb 20, 2009 10:47 pm
Re: Puzzle 23 - Distance to line segment
ChibaPet wrote:Is Sqr the square root in VB?.
Yes.
http://msdn.microsoft.com/en-us/library/aa263367(VS.60).aspx
I'll write a mathematical proof soon. So that (hopefully), it will be clear how this works. I wrote this code (actually, a slower, uglier version) several years ago, so I don't remember exactly how it was derived. If I recall correctly, I started with the equation for a couple of the lines, and then reduced the formulas a lot to get them in to this form. I tweaked them a lot to get them as fast as possible.
-George
-

gmmastros - LTD Admin

-











- Posts: 2222
- Joined: Tue Oct 09, 2007 5:19 pm
Re: Puzzle 23 - Distance to line segment
Entering equations is not the 'most fun' thing to do, so I wrote it out long hand. I hope nobody has any problem reading this. 
Xa, Ya is one point of the line segment and Xb,Yb is the other point. Xp,Yp is the point to calculate the distance for. Xi,Yi is the point on the line where the perpendicular 'distance' line intersect the line segment. In the drawing, it intersects within the end points, but it may end up being outside the end points. This mathematical proof does not take that in to account, but the VB code does.
Also.... shown below is the proof for the X intersect point. Calculations for the Y intersect point is not shown, but is sufficiently similar that is *probably* doesn't need to be shown.

You'll notice that this matches the equation I use in my algorithm for the x-intercept (where the distance line intersects the line segment). Immediately after the calculations, I check the X and Y values to make sure they are on the line. If not, I set them to the closest point.
Then, at the end, I calculate the distance using the normal distance calculation.

Xa, Ya is one point of the line segment and Xb,Yb is the other point. Xp,Yp is the point to calculate the distance for. Xi,Yi is the point on the line where the perpendicular 'distance' line intersect the line segment. In the drawing, it intersects within the end points, but it may end up being outside the end points. This mathematical proof does not take that in to account, but the VB code does.
Also.... shown below is the proof for the X intersect point. Calculations for the Y intersect point is not shown, but is sufficiently similar that is *probably* doesn't need to be shown.

You'll notice that this matches the equation I use in my algorithm for the x-intercept (where the distance line intersects the line segment). Immediately after the calculations, I check the X and Y values to make sure they are on the line. If not, I set them to the closest point.
Then, at the end, I calculate the distance using the normal distance calculation.
-George
-

gmmastros - LTD Admin

-











- Posts: 2222
- Joined: Tue Oct 09, 2007 5:19 pm
Re: Puzzle 23 - Distance to line segment
For what it's worth, I found a bug in my code. If the line segment is actually a point (distance = 0, x and y's are the same), my code calculates the wrong distance, which should actually be a simple point to point distance. Anyway, here's the corrected code.
The problem was right at the end where I check to see if the xInt is within xA and xB and is yInt is between yA and Yb. Notice the If/Else If blocks. I needed to add a special case where they are equal so that the intersect points would BOTH get set properly.
- Public Function PerpendicularDistanceToLine(ByVal xPoint As Single, ByVal yPoint As Single, ByVal xA As Single, ByVal yA As Single, ByVal xB As Single, ByVal yB As Single) As Single
- Dim Slope As Single
- Dim xInt As Single
- Dim yInt As Single
- If xA = xB Then
- xInt = xA
- yInt = yPoint
- ElseIf yA = yB Then
- xInt = xPoint
- yInt = yA
- Else
- Slope = ((yB - yA) / (xB - xA))
- xInt = (yPoint - yA + xA * Slope + xPoint / Slope) / (1 / Slope + Slope)
- yInt = (xPoint - xA + yA * Slope + yPoint / Slope) / (1 / Slope + Slope)
- End If
- If xA < xB Then
- If xInt < xA Then
- xInt = xA
- ElseIf xInt > xB Then
- xInt = xB
- End If
- ElseIf xA > xB Then
- If xInt < xB Then
- xInt = xB
- ElseIf xInt > xA Then
- xInt = xA
- End If
- ElseIf xA = xB Then
- xInt = xA
- End If
- If yA < yB Then
- If yInt < yA Then
- yInt = yA
- ElseIf yInt > yB Then
- yInt = yB
- End If
- ElseIf yB < yA Then
- If yInt < yB Then
- yInt = yB
- ElseIf yInt > yA Then
- yInt = yA
- End If
- ElseIf yA = yB Then
- yInt = yA
- End If
- PerpendicularDistanceToLine = Sqr((xInt - xPoint) * (xInt - xPoint) + (yInt - yPoint) * (yInt - yPoint))
- End Function
The problem was right at the end where I check to see if the xInt is within xA and xB and is yInt is between yA and Yb. Notice the If/Else If blocks. I needed to add a special case where they are equal so that the intersect points would BOTH get set properly.
-George
-

gmmastros - LTD Admin

-











- Posts: 2222
- Joined: Tue Oct 09, 2007 5:19 pm
Re: Puzzle 23 - Distance to line segment
gmmastros wrote:For what it's worth, I found a bug in my code. If the line segment is actually a point (distance = 0, x and y's are the same), my code calculates the wrong distance, which should actually be a simple point to point distance.
Just tested - mine seems to get that right. I still need to time it, though.
Okay. It's consistently taking five seconds to run a million times. I'm using the original problem, so it's running close to the longest code path - no horizontal or vertical shortcuts. No point reordering, but that's trivial anyway.
I'll get some microsecond resolution soon, and I'll get an average time per run.
- ChibaPet
- Apprentice

-
- Posts: 5
- Joined: Fri Feb 20, 2009 10:47 pm
Re: Puzzle 23 - Distance to line segment
May I suggest that
ElseIf yA = yB Then
can just be
Else
ElseIf yA = yB Then
can just be
Else
God cries a little bit every time someone builds a database.
-

Emtucifor - Guru

-










- Posts: 2832
- Joined: Fri May 30, 2008 9:30 pm
- Location: California
Re: Puzzle 23 - Distance to line segment
A solution based on a Python transcription of the Point class found in Squeak (http://squeak.org).
Trying to solve the same problem in Squeak is much easier since it already provides a Point class as part of the standard graphic primitives with all the methods for doing the calculation. Note the nice shorthand to instantiate a Point by sending the #@ message and the Y coordinate to a number.
Code is hidden, SHOW
Trying to solve the same problem in Squeak is much easier since it already provides a Point class as part of the standard graphic primitives with all the methods for doing the calculation. Note the nice shorthand to instantiate a Point by sending the #@ message and the Y coordinate to a number.
Code is hidden, SHOW
- natinja
- Newbie

-
- Posts: 2
- Joined: Tue Mar 03, 2009 1:10 am
Re: Puzzle 23 - Distance to line segment
Here's my solution in Java. It actually contains two solutions - the entire thing can basically be done with a built-in function, so as well as using that I went ahead and did the manual calculations for fun 

Code is hidden, SHOW
- GothGargoyle
- Apprentice

-
- Posts: 5
- Joined: Wed Mar 04, 2009 8:31 pm
Re: Puzzle 23 - Distance to line segment
it would be interesting to see the performance of the builtin function vs the various manual methods here... if anyone has the time to run them through
a smile is worth a thousand kind words, so smile, it's easy! 
CODE: $5
WORKING CODE: $500
PROPERLY DESIGNED & WORKING CODE: Priceless

CODE: $5
WORKING CODE: $500
PROPERLY DESIGNED & WORKING CODE: Priceless
-

damber - LTD Admin

-









- Posts: 3117
- Joined: Tue Oct 09, 2007 1:48 pm
- Location: North Wales, UK
26 posts • Page 1 of 2 • 1, 2



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.