I have a 2D array grid where each cell has a number in it, i would need a alghorithm that returns me the value of that cell depending on the X, Y position (0, 0 is bottom left)

number grid1

This is the grid in question, it can be infinite in size and "grows" in such a way that it always adds first the right outer edge, starting from the bottom and then goes to the left until it comes back to the edge. For example the next full "square" of this itteration would be:

enter image description here

What i would need a function that given x, y positions would return me that number. Example:

getValue(0, 0) = 0
getValue(0, 1) = 1
getValue(0, 2) = 4
getValue(1, 0) = 3
getValue(3, 3) = 12
getValue(6, 6) = 42
getValue(6, 0) = 48

The function should ofcourse calculate this value in some fashion and not get it from some premade grid of finite size, since the input of those value could be very large.


1 Answer 1


I am not sure if there is a direct way to compute the entries given the row and column, but here's one that works. Let $M$ be your matrix. The value of $M[i,j]$ is given by:

$$ M[i,j]=\begin{cases} j^2 + i & \text{if $j \ge i$ }\\ i^2 + 2i - j & \text{otherwise} \end{cases} $$

This comes from the observation that the values in the bottom row are perfect squares, that is $M[0,j] = j^2$ while those on the leftmost column are one less than a perfect square, $M[i,0] = (i+1)^2 - 1 = i^2 + 2i $. Other entries can be determined by computing their distance from either of the two.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.