The task here is simple: given a target location on an XY grid, and a rectangle on that grid, find the length of the shortest path from the origin to the target which does not intersect the rectangle.
All parameter values are integers. You can assume that neither the target point nor the origin is inside or on the border of the rectangle.
The rectangle can be specified in any reasonable format -- e.g. (<left x coordinate>, <top y coordinate>, <width>, <height>)
or (<left x coordinate>, <right x coordinate>, <top y coordinate>, <bottom y coordinate>)
.
For the purposes of these examples I will use the format (<left x coordinate>, <top y coordinate>, <width>, <height>)
.
Your answer must be within one percent of the true answer for any input (ignoring errors due to floating point).
Here is the example where the target coordinate is (5, 5)
(shown in green) and the rectangle has top left corner of (2, 4)
and width & height of (2, 3)
(shown in maroon). The shortest path is shown in orange.
In this case, the shortest path has length \$\sqrt{2^2+4^2} + \sqrt{1^2+3^2}\ \approx 7.63\$.
Note that the rectangle does not need to be obstructing the path between the origin and the target location -- take the same rectangle as the previous example, but with the target point of (-3, 5):
In this case, the answer is \$\sqrt{3^2 + 5^2} \approx 5.83\$.
Test cases
target x | target y | rectangle x | rectangle y | width | height | answer |
---|---|---|---|---|---|---|
5 | 5 | 2 | 4 | 2 | 3 | 7.6344136152 |
5 | 5 | 4 | 2 | 3 | 2 | 7.0710678119 |
-3 | 5 | 2 | 4 | 2 | 3 | 5.83095189485 |
0 | 0 | 100 | -50 | 50 | 30 | 0 |
0 | 100 | -1 | -2 | 3 | 4 | 100 |
8 | 0 | 1 | 2 | 3 | 4 | 9.7082039325 |
8 | 0 | 1 | 3 | 3 | 5 | 9.7082039325 |
Standard loopholes are forbidden. Since this is code-golf, the shortest program wins.
(0, 0), (5, 5)
so the answer should besqrt(5^2+5^2) = 7.07106781186548
. \$\endgroup\$