Forum Discussion
Patrick2788
Jul 18, 2023Silver Contributor
Formula Challenge: The most efficient way to generate a Number Spiral (Ulam spiral) ?
The goal: Ulam spiral - Wikipedia The trick is creating a function capable of producing the largest matrix of numbers possible (this may rule out the recursive approach). The approach ...
Patrick2788
Nov 21, 2024Silver Contributor
This is my rendition for 2024 with no Lambda helper functions.
//Patrick2788 11/21/2024
//Create a Ulam Spiral by supplying cartesian coordinates.
//Parameters:
//rings - Create a spiral with this many rings from the center starting value
//[start_at] - Specify a starting number. Defaults to 1 if omitted.
SpiralĪ» = LAMBDA(rings,[start_at],
LET(
start_at,IF(ISOMITTED(start_at),1,start_at),
//Create cartesian coordindates
i, SEQUENCE(rings * 2 + 1, , rings, -1),
j, SEQUENCE(, rings * 2 + 1, -rings, 1),
//Broadcast cartesian coordinates to matrices
x, j * SEQUENCE(rings * 2 + 1, , 1, 0),
y, i * SEQUENCE(, rings * 2 + 1, 1, 0),
//Four scenarios for Four quadrants:
//a_ - right b_ - left c_ - top d_ - bottom
a_, (ABS(x) > ABS(y)) * (x > 0),
b_, (ABS(x) > ABS(y)) * (x <= 0),
c_, (ABS(x) <= ABS(y)) * (y > 0),
d_, (ABS(x) <= ABS(y)) * (y <= 0),
//Calculations for each quadrant:
a, 4 * x ^ 2 - 3 * x + y,
b, 4 * x ^ 2 - x - y,
c, 4 * y ^ 2 - y - x,
d, 4 * y ^ 2 - 3 * y + x,
//Check cartesian coordinates, apply calculations
result, start_at+IF(a_, a, IF(b_, b, IF(c_,c, d))),
result
)
);