I've been wondering if it's possible to solve this problem in recursive or "divide and conquer" way. Here is visualisation of my problem:
Input:
22 // point no 1
35 // point no 2
5 // ...
44
45
20
46
Output: 2 // point with number 2 has got the lowest sum (87)
I know how to do this in an iterative way, but I'm thinking about something more optimal.
The shortest distance between two points is a straight line. This distance can be calculated by using the distance formula. The distance between two points ( x 1 , y 1 ) and ( x 2 , y 2 ) can be defined as d = ( x 2 − x 1 ) 2 + ( y 2 − y 1 ) 2 .
To calculate the distance between a point and a straight line we could go step by step (calculate the segment perpendicular to the line from the line to the point and the compute its length) or we could simply use this 'handy-dandy' equation: d = |Ax1 + By1 + C | / √(A2 + B2) where the line is given by Ax+By+C = 0 and ...
This is called the median value. Just sort the values and select the center. If n is even, any of the two center values will do.
There are also O(n) algorithms for calculating the median.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With