O wait, I do have a question. Does anyone know how to extract the row and position in the row(and the other way around) from a pyramid thing like this:
1
2 3 4
5 6 7 8 9
Where the pyramid has n rows. I am passing around the n and the number of the tile, or should I just scrap that plan and make some weird 2 dimensional array?
Let's see. If we store everything in a 1D array...
If the first element is at index = 0 and the nth row contains 2n+1 elements, then recursively: Let the starting index of the nth row be designated as r
n.
Base-case: r
0 = 0
Recursion: r
n = r
n-1 + 2(n-1) + 1 = r
n-1 + 2n-1
Or directly, r
n = n
2The last index of the nth row: m
n = r
n + 2n
Now, assuming the elements exist, their positions in an array can thus be described with a function P(i,n), where i is an element's local index in the nth row. The function returns the array index of the element.
Local boundaries: 0 <= i <= 2n
P(i,n) = r
n + i, -1 if i is outside local boundaries.
Neighbours:
Let's define i as the local index of the element and n as the nth row index.
If i = 0, then it has no left neighbour. If i = 2n (or last element of array), then it has no right neighbour. Both of these have no upper neighbour either, but they have below.
All others have neighbours above and below.
The function L(i,n) returns array index of the left neighbour.
L(i,n) = P(i-1,n), local: 0 < i <=2n, -1 if outside
The function R(i,n) returns array index of right neighbour.
R(i,n) = P(i+1,n), local: 0 <= i <2n, -1 if outside
The function U(i,n) returns the array index of the upper neighbour.
U(i,n) = P(i-1,n-1), local: 0 < i <2n, n > 0, -1 if outside
The function B(i,n) returns the array index of the lower neighbour.
B(i,n) = P(i+1,n+1), local: 0 <= i <= 2n, -1 if outside
As usual, whenever using these functions, remember to check if the elements actually exists to avoid exceptions.