Hacker News new | ask | show | jobs
by papa2fire 478 days ago
To understand recursion, and given that we know the initial value of r (r=4), I suggest replacing the recursive calls with a simple copy-paste of the function body. You’ll see that it’s just four nested loops each one iterating over the 14 dimensions and making changes to them. Each loop starts at the next dimension after the previous one, ensuring that changes are only made in increasing order. This is the key to avoiding duplicates—each pair of modified dimensions is generated only once (e.g., 1&2 is generated, but 2&1 is not). This is controlled by the last parameter (min), which defaults to 0 and sets the starting value of the loops. Another way to see it is that the function returns the sum of neighbors up to distance r, but only by making changes in dimensions equal to or greater than 'min'.
1 comments

Is the recursion relation you use https://en.wikipedia.org/wiki/Hockey-stick_identity ? Are you sure you can't use https://en.wikipedia.org/wiki/Pascal%27s_rule instead for a simpler recursion. Have you also tried using https://en.wikipedia.org/wiki/Vandermonde%27s_identity ?
Ohh, very interesting, thanks! I’m not entirely sure, but yes, I’d say my naive implementation uses the hockey stick principle. That said, I think many implementations are possible. We could also eliminate recursion by using an index array to store the values of 'min' variable, but I think that would make the behavior harder to understand.

In any case, the key point in my view is that there are 19,321 neighbors at distance ≤4. If we assume as an input condition that their values can be arbitrary—that is, the value of one neighbor has no relation to the others—then regardless of the implementation or mathematical identity used, we’ll end up performing 19,320 summations.

It’s a different story if we want to repeat this process for multiple points. In that case, we can optimize, since some neighbors might be shared and summed only once. This is exactly what my algorithm does: by handling everything in a matrix-based way, it reduces the number of summations per point to just 101 instead of 19,321. I’m not sure if there’s a specific mathematical identity behind this. In fact, I asked on StackExchange but haven’t had much success: https://math.stackexchange.com/questions/5040947/efficient-a...