Imagine a NxN chess board, I have a tuple t = (0,3,2,1) which represents chess pieces location at each column (col = index), and each number represents the row, starting at 0 from bottom.
For this example, it has 4 columns, first piece is at row=0 (bottom row), second piece is on row=3 (fourth/highest row), third piece is on row=2 (third row from bottom), fourth piece is on second row from bottom.
I would like to represent it as a 2D array as follows:
[[0,1,0,0],
[0,0,1,0],
[0,0,0,1],
[1,0,0,0]]
I was able to generate the 2D array using this code
pieces_locations = (0,3,2,1)
pieces_locations = list(pieces_locations)
table_size = len(pieces_locations)
arr = [[0 for col in range(table_size)] for row in range(table_size)]
However, I was not able to assign the 1’s in their correct locations.
I was able to understand this: arr[row][col], but the rows are inverted (0 is top to N is bottom).
>Solution :
Use this after you’ve made the list (A matrix of 0s)
** If the locations list is not as long as the number of rows, the program will crash (use try and except to counter)
for x, i in enumerate(range(1, len(arr))):
arr[-i][pieces_locations[x]] = 1
This should give you your desired output, I hope this helps