stevenvh.net

Floobydust

Programming tip: “pyramid function”

pyramid
“pyramid function” for square of even size.

Some time ago I wanted an N x N square matrix for a POV-Ray scene, with in each cell a number depending on its distance from the edge. The cells at the edge get a value of 0, the ones bordering those get a value of 1, and so on. You can think of the numbers as the heights in a step pyramid, as shown in the image.

Writing a function for this isn't hard, even for a novice; it usually involves a few nested loops and a bit of range testing. And it doesn't look pretty.
I thought there should be a simple one-line function which you feed the square size N, and the cell coordinates (X, Y) and it returns the height Z at that point (if you stick to the pyramid paradigm).

Indeed, I found the following function:

$ Z = (N - 1 - abs(X - Y) - abs(X + Y - N + 1)) / 2 $

That's if your X and Y are in the range [0 .. N-1]. If you prefer the range [1 .. N] you only have to change one of the signs:

$ Z = (N - 1 - abs(X - Y) - abs(X + Y - N {\color{red}-} 1)) / 2 $

That's all there is to it, really. The image is POV-Ray's rendering of a script I wrote to test the function. (It works for odd values of N as well.)