My world
Imagine a 1 dimensional discrete world where there are poles. Let's represent this world by a 1D grid where each slot either contains a pole I or does not contains a pole -
--------I-I---------I----II-------I-------------I--
In this world there are n slots and m poles. We can represent this world either with a vector of length m listing the positions of the poles
std::vector<unsigned int> polePositions;
or with a boolean vector of the length n
std::vector<bool> isThereAPole;
Statistic of interest and example
Each slot has an average distance (averageDistance) to all poles. For example, below the slot index 2 (zero based counting)
---I-I
has an average distance to the poles of
averageDistance = (1 + 3) / 2 = 2
We can then compute this average distance for each slot and average them out to get the average average distance (averageAverageDistance). For the above example,
averageAverageDistance = ((3 + 5) / 2 + (2 + 4)/2 + (1+3)/2 + (0+2)/2 + (1 + 1)/2 + (2+0)/2)/6 = 12/6 = 2
Question
How to compute this averageAverageDistance with high performance?
Typically, I'll have about n=1e6 slots and about m=1e5 poles at each call of the function. n will remain the same at every call of the function but m (and polePositions or isThereAPole) will vary among function calls.
Bad implementation
Here is a simple implementation using the above small data as example
#include <iostream>
#include <vector>
#include <math.h>
double getAverageAverageDistance(std::vector<unsigned int> polePositions, int n)
{
double averageAverageDistance = 0.0;
for (int slot = 0 ; slot < n ; slot++)
{
double averageDistance = 0.0;
for (auto& polePosition : polePositions)
{
averageDistance += fabs(slot - polePosition);
}
averageDistance /= polePositions.size();
averageAverageDistance += averageDistance;
}
averageAverageDistance /= n;
return averageAverageDistance;
}
int main()
{
std::vector<unsigned int> polePositions;
polePositions.push_back(3);
polePositions.push_back(5);
int n = 6;
std::cout << "averageAverageDistance = " << getAverageAverageDistance(polePositions, n) << "\n";
}
which correctly outputs
averageAverageDistance = 2
This program has time complexity O(n m). Is there a better solution?