Task 5 of 6
Time to combine everything: a 5-tap moving average. Each output
cell is the mean of signal[x−2 … x+2] — a gather over a small
window of neighbors, with clamping where the window hangs off either end. This
shape — loop over a fixed window, clamp, accumulate — is called a
stencil, and it powers blurs, edge detectors, and physics simulations
alike.
Yes, a loop inside the kernel is fine: it's 5 iterations of private arithmetic per thread, not a loop over the data. 128 threads each averaging 5 numbers is still one parallel pass.
0 … n−1.for (let d = 0; d < 5; d++) with offset d − 2Math.max(0, Math.min(n − 1, …))5The five indexes are this.thread.x + d - 2 for
d = 0…4: two to the left, itself, two to the right.
Each iteration:
const j = Math.max(0, Math.min(this.constants.n - 1, this.thread.x + d - 2));
sum += signal[j];Cell 0's clamped window reads indexes 0, 0, 0, 1, 2 — so
out[0] should equal (3·signal[0] + signal[1] + signal[2]) / 5.
This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.