user12973342
user12973342

Reputation:

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

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

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.

Upvotes: 0

Views: 944

Answers (1)

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

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

Upvotes: 1

Related Questions