# Fastest way to perform math on section of 2D array (less for loops)?

I am currently translating my code from Python into C++, which I am new to. In the script, a droplet of water, whose x-y position is represented by a 2-element array of floats pos[], needs to alter nearby points on a 2d array heightmap[][]. This heightmap stores one "height" value between 0 and 1 at each pair of indices (one for x, one for y). The goal is that the droplet will affect the points on the heightmap within a certain constant radius, which means the distance to each nearby point must be calculated. The change in height of each point will also be weighted by the inverse of the distance, as well as the sum of all valid distances to ensure uniform distribution.

The trouble is performance, as this requires many for loops. Two pairs of nested loops, each of which must execute many steps depending on the radius constant. This whole function will be called up to 40 times per "droplet" and the simulation uses literally tens of thousands of said droplets. The performance overall isn't terrible, but I feel as though there is a much simpler solution that I am unaware of, either in the way the heightmap is represented (is a 2d array like this the best way to go?) or how it is referenced. Nothing I found while searching seemed useful. Any help is appreciated!

```
void erode(float pos[], float deltaSediment) {
int x = floor(pos[0]);
int y = floor(pos[1]);
float brush[2 * radius][2 * radius];
float sum = 0;
float dist = 0;
for (int u = 1; u < 2*radius; u++) {
for (int v = 1; v < 2*radius; v++) {
dist = distance(u + x - radius, v + y - radius, pos[0], pos[1]);
if (dist <= radius) {
brush[u][v] = 1/distance(u + x - radius, v + y - radius, pos[0], pos[1]);
sum += dist;
}
else {
brush[u][v] = 0;
}
}
}
for (int u = 1; u < 2*radius; u++) {
for (int v = 1; v < 2*radius; v++) {
heightmap[u + x - radius][v + y - radius] -= deltaSediment * brush[u][v] / sum;
}
}
}
```

do you know?

how many words do you know