# Calculate smallest distance between two objects from two different arrays

Hi everybody!
So, this is the problem: I have an array of objects that are attracted by every object of another array (for example if in the first array I have three spheres, they are attracted by every sphere of the other array in equal way). All the objects are initialized with random positions.
Now I want that the spheres from the first array would be attracted from just the nearest of the spheres in the second array, and not by everyone in the same way.
I have tried with this:

``````for(int i = 0; i < sizeFirstArray; i++) {
for(int j = 0; j < sizeSecondArray; j++) {
distance[j] = checkDistance(array1[i], array2[j]);  //this function calculates the distance
}
smallestDistance = std::min(std::min(distance[0], distance[1]), distance[2]); /*his should store the smallest  distance */
}
``````

With the smallest distance I can figure something out, but I don’t think that this is working (I haven’t tested yet).
Thanks everybody for every kind of help

it looks to me like you are only calculating the smallest distance among the first three elements (distance[0], distance[1], distance[2]). don’t you mean to make the `smallestDistance` calculation for each element j? does this do what you need?

``````for(int i = 0; i < sizeFirstArray; i++) {
float smallestDistance = INFINITY;
int indexClosest = -1;
for(int j = 0; j < sizeSecondArray; j++) {
float distance = checkDistance(array1[i], array2[j]);
if (distance < smallestDistance) {
smallestDistance = distance;
indexClosest = j;
}
}
// after this loop terminates, indexClosest is the j which is closest to i
}``````

Thank you very much! This is exactly what I needed