0

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).

3
  • Why do you need to convert the tuple to a list? Commented Nov 17, 2022 at 19:42
  • For the example above, starting from the first array (highest row) -> let index of (table_size - 1) = 1, row below -> let index of (table_size - 2) = 1, ... last array (bottom row) -> let index of (0) = 1 Commented Nov 17, 2022 at 19:44
  • That doesn't explain why you need to do pieces_location = list(pieces_location). You never modify it, so you can use the tuple the same as the list. Commented Nov 17, 2022 at 19:46

3 Answers 3

1

First create the 2-d list of zeroes.

arr = [[0] * table_size for _ in range(table_size)]

Then loop over the locations, replacing the appropriate elements with 1.

for col, row in enumerate(pieces_location, 1):
    arr[-row][col] = 1
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

I was able to figure it out, although I'm sure there is a move convenient way.

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)]


for row in range(0, table_size):
        arr[row][pieces_locations.index(row)] = 1


res = arr[::-1]
print (res)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.