Minimum Sum of Euclidean Distances to all given Points - GeeksforGeeks

11 May, 2021
Given a matrix mat[][] consisting of N pairs of the form {x, y} each denoting coordinates of N points, the task is to find the minimum sum of the Euclidean distances to all points.
Examples:
Input: mat[][] = { { 0, 1}, { 1, 0 }, { 1, 2 }, { 2, 1 }} Output: 4 Explanation: Average of the set of points, i.e. Centroid = ((0+1+1+2)/4, (1+0+2+1)/4) = (1, 1). Euclidean distance of each point from the centroid are {1, 1, 1, 1} Sum of all distances = 1 + 1 + 1 + 1 = 4Input: mat[][] = { { 1, 1}, { 3, 3 }} Output: 2.82843
Approach: Since the task is to minimize the Euclidean Distance to all points, the idea is to calculate the Median of all the points. Geometric Median generalizes the concept of median to higher dimensions
Follow the steps below to solve the problem:
Calculate the centroid of all the given coordinates, by getting the average of the points.
Find the Euclidean distance of all points from the centroid.
Calculate the sum of these distance and print as the answer.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate Euclidean distancedouble find(double x, double y,            vector<vector<int> >& p){     double mind = 0;    for (int i = 0; i < p.size(); i++) {         double a = p[i][0], b = p[i][1];        mind += sqrt((x - a) * (x - a)                     + (y - b) * (y - b));    }     return mind;} // Function to calculate the minimum sum// of the euclidean distances to all pointsdouble getMinDistSum(vector<vector<int> >& p){     // Calculate the centroid    double x = 0, y = 0;    for (int i = 0; i < p.size(); i++) {        x += p[i][0];        y += p[i][1];    }    x = x / p.size();    y = y / p.size();     // Calculate distance of all    // points    double mind = find(x, y, p);     return mind;} // Driver Codeint main(){     // Initializing the points    vector<vector<int> > vec        = { { 0, 1 }, { 1, 0 }, { 1, 2 }, { 2, 1 } };     double d = getMinDistSum(vec);    cout << d << endl;     return 0;}
// Java program to implement// the above approachclass GFG{ // Function to calculate Euclidean distancestatic double find(double x, double y,                   int [][] p){    double mind = 0;         for(int i = 0; i < p.length; i++)    {        double a = p[i][0], b = p[i][1];        mind += Math.sqrt((x - a) * (x - a) +                          (y - b) * (y - b));    }    return mind;} // Function to calculate the minimum sum// of the euclidean distances to all pointsstatic double getMinDistSum(int [][]p){         // Calculate the centroid    double x = 0, y = 0;    for(int i = 0; i < p.length; i++)    {        x += p[i][0];        y += p[i][1];    }         x = x / p.length;    y = y / p.length;     // Calculate distance of all    // points    double mind = find(x, y, p);     return mind;} // Driver Codepublic static void main(String[] args){         // Initializing the points    int [][]vec = { { 0, 1 }, { 1, 0 },                    { 1, 2 }, { 2, 1 } };     double d = getMinDistSum(vec);         System.out.print(d + "\n");}} // This code is contributed by Amit Katiyar
# Python3 program to implement# the above approachfrom math import sqrt # Function to calculate Euclidean distancedef find(x, y, p):     mind = 0    for i in range(len(p)):        a = p[i][0]        b = p[i][1]        mind += sqrt((x - a) * (x - a) +                     (y - b) * (y - b))                          return mind # Function to calculate the minimum sum# of the euclidean distances to all pointsdef getMinDistSum(p):     # Calculate the centroid    x = 0    y = 0         for i in range(len(p)):        x += p[i][0]        y += p[i][1]             x = x // len(p)    y = y // len(p)     # Calculate distance of all    # points    mind = find(x, y, p)     return mind # Driver Codeif __name__ == '__main__':     # Initializing the points    vec = [ [ 0, 1 ], [ 1, 0 ],            [ 1, 2 ], [ 2, 1 ] ]     d = getMinDistSum(vec)    print(int(d)) # This code is contributed by mohit kumar 29
// C# program to implement// the above approachusing System;class GFG{ // Function to calculate Euclidean distancestatic double find(double x, double y,                   int [,] p){    double mind = 0;         for(int i = 0; i < p.GetLength(0); i++)    {        double a = p[i,0], b = p[i,1];        mind += Math.Sqrt((x - a) * (x - a) +                          (y - b) * (y - b));    }    return mind;} // Function to calculate the minimum sum// of the euclidean distances to all pointsstatic double getMinDistSum(int [,]p){         // Calculate the centroid    double x = 0, y = 0;    for(int i = 0; i < p.GetLength(0); i++)    {        x += p[i,0];        y += p[i,1];    }         x = x / p.Length;    y = y / p.Length;     // Calculate distance of all    // points    double mind = find(x, y, p);     return mind;} // Driver Codepublic static void Main(String[] args){         // Initializing the points    int [,]vec = { { 0, 1 }, { 1, 0 },                    { 1, 2 }, { 2, 1 } };     int d = (int)getMinDistSum(vec);         Console.Write(d + "\n");}} // This code is contributed by Rohit_ranjan
<script> // JavaScript program for the above approach // Function to calculate Euclidean distancefunction find(x, y, p){    let mind = 0;           for(let i = 0; i < p.length; i++)    {        let a = p[i][0], b = p[i][1];        mind += Math.sqrt((x - a) * (x - a) +                          (y - b) * (y - b));    }    return mind;}   // Function to calculate the minimum sum// of the euclidean distances to all poletsfunction getMinDistSum(p){           // Calculate the centroid    let x = 0, y = 0;    for(let i = 0; i < p.length; i++)    {        x += p[i][0];        y += p[i][1];    }           x = x / p.length;    y = y / p.length;       // Calculate distance of all    // polets    let mind = find(x, y, p);       return mind;}     // Driver Code             // Initializing the points    let vec = [[ 0, 1 ], [ 1, 0 ],               [ 1, 2 ], [ 2, 1 ]];       let d = getMinDistSum(vec);           document.write(d);                      </script>
4
Time Complexity: O(N) Auxiliary Space: O(1)
amit143katiyar
Rohit_ranjan
mohit kumar 29
sanjoy_62
median-finding
Arrays
Geometric
Mathematical
Arrays
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Window Sliding Technique
Program to find sum of elements in a given array
Move all negative numbers to beginning and positive to end with constant extra space
Reversal algorithm for array rotation
Find duplicates in O(n) time and O(1) extra space | Set 1
Closest Pair of Points using Divide and Conquer algorithm
How to check if two given line segments intersect?
How to check if a given point lies inside or outside a polygon?
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)