So I have a 4x4 matrix like so
|0 1 2 3
-+-------
0|0 1 3 6
1|2 4 7 a
2|5 8 b d
3|9 c e f
and I am traversing it in the order specified by the hexadecimal characters in it. so start at (0, 0), then (1, 0), (0, 1), (2, 0), (1, 1), (0, 2)...
So here is the code:
def diagonal(n):
for a in range(n):
for b in range(a + 1):
yield a - b, b
for a in range(n - 1):
for b in range(n - a - 1):
yield n - b - 1, b + 1 + a
iterating through this gives
for x, y in diagonal(4):
print((x, y))
# (0, 0)
# (1, 0)
# (0, 1)
# (2, 0)
# (1, 1)
# (0, 2)
# (3, 0)
# (2, 1)
# (1, 2)
# (0, 3)
# (3, 1)
# (2, 2)
# (1, 3)
# (3, 2)
# (2, 3)
# (3, 3)
which is exactly as I intended. The part I am stuck on is trying to make a function where I give it the index, and it gives me the coordinates. So for my 4x4 matrix,(this is still in hexadecimal)
0 -> (0, 0)
1 -> (1, 0)
2 -> (0, 1)
3 -> (2, 0)
4 -> (1, 1)
5 -> (0, 2)
6 -> (3, 0)
7 -> (2, 1)
8 -> (1, 2)
9 -> (0, 3)
a -> (3, 1)
b -> (2, 2)
c -> (1, 3)
d -> (3, 2)
e -> (2, 3)
f -> (3, 3)
I have intentions to move on to variable sized square matrices so I cannot just hard code these values into a dict.
I have been tinkering for hours trying to get this to work but I cannot for the life of me get it to work.
This is not homework, just something I'm working on in my spare time, and it's slowly driving me up the wall.
If anything is not clear please don't hesitate to ask.
Thanks in advance.
Edit: I presume someone will comment about this post Traverse Matrix in Diagonal strips which is similar but as with my first function this only iterates over the coordinates, and I cannot work out the coordinates from an index.