i will test it in a while, can you explain the logic behind it? if it works its better then what i have and thank you.
You're welcome!
And sure, I can.
Let's call (the border of) a rectangle with as center the origin (0,0) a cycle of the spiral.
The n-th cycle is a rectangle with with vertices (-n, -n), (-n, n), (n, -n) and (n, n).
The n-th cycle then has 8*n amount of squares in itself, except for the zeroth cycle, which has exactly 1 square (0, 0).
You can verify this to be true by induction.
You know the first cycle has 8 squares.
The n-th cycle can be build by taking the (n-1)-th cycle, move its corners 1 square diagnally away from the origin,
by moving all the squares on the left edge 1 square to the left, by moving all the squares on the right edge 1 square to the right,
by moving all the squares on the top edge 1 square upwards and by moving all the squares on the bottom edge 1 square downwards.
You'll then always need 8 additional squares to complete the n-th cycle, so the n-th cycle contains 8 squares more than the (n-1)-th cycle.
This completes the proof by induction.
Now, we can prove that the value of the squares at positions (n, -n) equal the amount of squares in all k-th cycles with 0 < k < n + 1.
You can understand this as follows:
The square (n, -n) is the last square of the n-th cycle the spiral goes through.
Since the value of a square equals the amount of preceding squares on the spiral, ignoring the square (0, 0), we know the above is true.
So, now we want to know the sum of 8*k with 0 < k < n + 1.
This sum equals 8*(n(n+1)/2), which equals n*(n+1)*4.
This is what I calculated in the vars in my script.
n is such that (X, Y) is a square of the n-th cycle in te spiral.
m is the value of the last square in the n-th cycle.
Now, if we don't have square (n, -n), but we ave another square on the top edge of the cycle of the form (X, -n),
then we know that there are exactly n - X amount of squares between the last square of the cycle and the input square (including the input square, but excluding the last square).
Thus we know that the value of (X, -n) is m - (n - X).
This is what you see in my first if-statement and return-statement.
Now, suppose we have a square at the right edge of the cycle, of the form (-n, Y).
We know the value of (-n, -n), because it is a square at the top edge, so its value is m - (n - (-n)) = m - 2*n.
Similarly to last time, we know that there are exactly Y - (-n) amount of squares between (-n, Y) and (-n, -n),
so the value of (-n, Y) is m - 2*n - (Y + n).
This is exactly what I do in the second if-statement and return-statement.
Analogously, you can calculate the values of squares on the bottom and right edge of the cycle.