Hello,

I'm trying to calculate the maximum and minimum distance between 10 points. My method to calculate the maximum distance is working fine however my method to calculate the minimum is returning 0.0 and I'm not sure why. Could someone please take a look at my code and tell me what I have missed? The only difference between my max and min methods is the greater than and less than within the if statement.

public static double min(double[] x, double[] y, double[] z) {
    double distance[] = new double[45];
    double minDistance = 0;
    int count = 0;

    for (int i = 0; i < 10; i++) {
        for (int j = i + 1; j < 10; i++) {
            distance[count] = Math.sqrt(Math.pow(x[i] - x[j], 2) + Math.pow(y[i] - y[j], 2) + Math.pow(z[i] - z[j], 2));

            if (distance[count]) < minDistance) {
                minDistance = distance[count];
            }
        }
    }

    return minDistance;
}

can you provide a bit more information? what do you mean 'distance'? can you explain that in words? since we're not talking about coördinates, how are you calculating it (or how should it be calculated)?

Look at your initial value for minDistance. Do you think you will ever find a smaller value than that? So the if test on line 10 will always be false.

Start minDistance at some very large value (larger than any distance you will calulate) Integer.MAX_VALUE would be the obvious choice.

Hi,
First what role have variable "count", because is allways 0. distance[count] is allways first element of the array in your code.
Line 7: for (int j = i + 1; j < 10; i++)
Why i++ and not j++ ? I supouse it's an error here.

Try this:

 public static double min(double[] x, double[] y, double[] z) {
        double distance;
        double minDistance = 0;
        for (int i = 0; i < 10; i++) {
            for (int j = i + 1; j < 10; j++) {
                distance = Math.sqrt(Math.pow(x[i] - x[j], 2) + Math.pow(y[i] - y[j], 2) + Math.pow(z[i] - z[j], 2));
                if(minDistance == 0)
                {
                    minDistance = distance;
                }
                else
                {
                    if (distance < minDistance) {
                        minDistance = distance;
                }
            }
        }
    return minDistance;
    }
if(minDistance == 0) {
   minDistance = distance;

Not such a good idea if two of the points are at the same position (and nobody has said they can't be), in which case they will be the closest pair, and the distance really will be zero. This code will then replace that with the next distance, even though it's bigger.
Much better to initialise minDistance properly (see previous post)

Thank you, James! I knew I was missing something obvious.

This question has already been answered. Start a new discussion instead.