Hello,

I'm trying to develop an algorithm/program that calculates the distance between two points. These values are stored inside a 1D array, which, acts as a 2D array (I think you know what I mean!) The values are:

150 50
15 20

The calculation should therefore be:

d = √(150 - 15)² + (50 - 20)²

Here is the code I've written (Ok, I know it's not the best way, just testing):

#include <iostream>
#include <math.h>
using namespace std;
int main(int argc, char *argv[]) {

    int coord[2*2] = {150, 50, 
                      15, 20};

    double distance = 0;
    double dis1 = 0;
    double dis2 = 0;

    for(int i=0; (i < 2); i++)
    {
        for(int j=0; (j < 2); j++)
        {
            dis1 = (coord[i*2+j]-coord[i*2+j])*(coord[i*2+j]-coord[i*2+j]);
            dis2 = (coord[i*2+j]-coord[i*2+j])*(coord[i*2+j]-coord[i*2+j]);

        }
        cout << endl;
    }

    distance = sqrt(dis1+dis2);

    cout << distance;
}

Anyone offer any solutions?

Thanks :)

I kind of see what you are trying to do with the nested for() loops but it is wrong.

For distance I would just make a function that takes in the two coordinates, or this 4 element array, and then just plug it into the formula.

Also in C++ you want to use the cmath library for math and not the math.h C version.

#include <iostream>
#include <cmath>

using namespace std;

double Distance(int x1, int y1, int x2, int y2)
{
    return sqrt((x2-x1)*(x2-x1) + (y2-y1)*(y2-y1));
}

double Distance( int coords[4] )
{
    return sqrt((coords[2]-coords[0])*(coords[2]-coords[0]) + (coords[3]-coords[1])*(coords[3]-coords[1]));
}

int main(int argc, char *argv[]) {

    int coord[2*2] = {150, 50,
                      15, 20};

    cout << Distance(coord[0], coord[1], coord[2], coord[3]) << endl;
    cout << Distance(coord) << endl;
}
Comments
Thank you! :)!!!

@Ancient Dragon

What if there is more than 4 coords? If it was dynamically populated? (I will eventually change this to a vector)..

But, if the image had 3 points on it, there'd be 6.. Would I need a loop then?

Yeah if you wanted to have it work for 2D and 3D points then you could either overload the function to do both 2D and 3D "hardcoded" or you can use a loop to sum all the squares then take a single squareroot at the end.

Example

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

double Distance(vector<double> pt1, vector<double> pt2)
{
    if( pt1.size() != pt2.size() )
        return 0;

    double sum = 0;
    for( unsigned int i = 0; i < pt1.size(); i++ )
        sum += (pt2[i]-pt1[i])*(pt2[i]-pt1[i]);

    return sqrt(sum);
}

int main(int argc, char *argv[])
{
    vector<double> pt1, pt2;
    pt1.push_back(150);
    pt1.push_back(50);
    pt2.push_back(15);
    pt2.push_back(20);

    cout << Distance(pt1, pt2) << endl;
}
This question has already been answered. Start a new discussion instead.