1
votes

I discovered this pattern and decided to print it.

1  2  5  10 17
3  4  7  12 19
6  8  9  14 21
11 13 15 16 23
18 20 22 24 25

Rule here is to move from (0,0) to (0,1) to (1,0) to (1,1) to (0,2) to (2,0) to (1,2) to (2,1) to (2,2) and so on upto NxN matrix.

I have a very complex approach for printing it. Is there any easy way to print this pattern?

Update: Added one more row and column

2
How are you storing the said pattern? Is it just a nested array, List or similar? Do you just want pseudo code? - Draken
I am filling the elements of last row and last column of the matrix alternatively, and once I reach (N,N) , I create 1 more row and column, then repeating it. - BuggerNot
Storing it in a 2d matrix. - BuggerNot

2 Answers

4
votes

It seems like the general rule is as follows:

Given a position as a tuple (n, m), the next position is

  • (n+1, 0), if n = m
  • (m, n), if n > m
  • (m, n+1), if n < m

In Python:

def next_pos(n, m):
    if n == m: return (n+1, 0)
    if n >  m: return (m, n)
    if n <  m: return (m, n+1)

Example:

N = 5
n, m = (0, 0)
matrix = [[None for _ in range(N)] for _ in range(N)]
for x in range(N*N):
    matrix[m][n] = x+1
    n, m = next_pos(n, m)

Result:

1   2   5   10  17
3   4   7   12  19
6   8   9   14  21
11  13  15  16  23
18  20  22  24  25
1
votes

Here is a Python solution that first extends every row by every other number starting with 1 more than the last perfect square, and then adds a new row, which consists of every other number starting with 2 more than the last perfect square, along with the final entry (which is the next perfect square in the sequence):

def expandSquare(square):
    n = len(square[0])
    for i, row in enumerate(square):
        row.append(n**2 + 1 + 2*i)
    square.append([k for k in range(n**2 + 2, (n+1)**2,2)] + [(n+1)**2])

def makeSquare(n):
    square = [[1]]
    for i in range(1,n): expandSquare(square)
    return square

def pprint(square):
    print('\n'.join('\t'.join(str(i) for i in row) for row in square))

For example,

>>> pprint(makeSquare(5))
1   2   5   10  17
3   4   7   12  19
6   8   9   14  21
11  13  15  16  23
18  20  22  24  25