samedi 23 février 2019

How to calculate centroid of vector of vectors using stl algorithms (accumulate and for_each)

I wrote program which generate 100 points in n dimension space and calculate centroid(geometric center). It works well but I need to write this part without using for loop, only using accumulate, for_each and arithmetic functors.

int dimensions = 2; 
int number_of_points = 100;
vector<vector<double>> cloud_A(number_of_points, vector<double>(dimensions, 0));
for_each(cloud_A.begin(), cloud_A.end(), RandomGenerator(5, 10));
vector<double> centroid_A(dimensions, 0);

for (int i = 0; i < dimensions; i++){
    centroid_A[i] = accumulate(chmura_A.begin(), chmura_A.end(), 0.0, Suma(i));
}   
for_each(centroid_A.begin(), centroid_A.end(), Divide(number_of_points));

I stuck for few hours, wondering if it's even possible, my closest bet would be, if cloud_A.begin()[count] would work:

int count = 0;
for_each(centroid_A.begin(), centroid_A.end(), [&](double d){
    for_each(cloud_A.begin()[count], cloud_A.end()[count], [&](double punkt) {
        centroid_A[count]=accumulate(punkt.begin(), punkt.end(), 0.0, plus<double>()) << endl;
        });
        count++;
    });

Aucun commentaire:

Enregistrer un commentaire