Home > Net >  How to create a 2D array of size nxn according to the following rules?
How to create a 2D array of size nxn according to the following rules?

Time:02-12

How can I create a 2D array of size nxn according to the following rules:

  • On the main diagonal put 0
  • On the diagonal adjacent to main put 1
  • On the next diagonal put 2, and so forth

Example:

n = 5
        
output = [[0, 1, 2, 3, 4],
          [1, 0, 1, 2, 3],
          [2, 1, 0, 1, 2],
          [3, 2, 1, 0, 1],
          [4, 3, 2, 1, 0]]

Preferably I would like to print every row on a single line.

I probably has to do with 2D array offsets, but more than that I am stumped.

CodePudding user response:

You can find the grid distance of each cell by doing abs(i - j). When they're equal, then you must be on the diagonal, so the difference is zero. One off the diagonal would make the difference 1, two off the diagonal would be 2, etc.

This is easy to do in a nested list comprehension:

n = 5
output = [[abs(i - j) for i in range(n)] for j in range(n)]

# print each row on its own line
import pprint
pprint.pprint(output)
# [[0, 1, 2, 3, 4], 
#  [1, 0, 1, 2, 3], 
#  [2, 1, 0, 1, 2], 
#  [3, 2, 1, 0, 1], 
#  [4, 3, 2, 1, 0]]
  • Related