Print 1..N² in NxN matrix, starting at bottom-right and zig-zag

Question:

Given an input n, I want to print n lines with each n numbers such that the numbers 1 through are displayed in a zig-zag way, starting with 1 appearing at the bottom-right corner of the output matrix, and 2 at the end of the one-but-last row, …etc.

Examples:

Given Input 3.

Print:

9 4 3
8 5 2
7 6 1

Given Input 1.

Print:

1

Given Input 4.

Print:

 13 12 5 4
 14 11 6 3
 15 10 7 2
 16 9 8 1

Attempt

n = int(input("Enter dimensions of matrix :"))
m = n
x = 1
columns = []
for row in range(n):
    inner_column = []
    for col in range(m):
        inner_column.append(x)
        x = x + 1
    columns.append(inner_column)
for inner_column in columns:
    print(' '.join(map(str, inner_column)))

I’ve tried something like this, but it prints out the array incorrectly. Any ideas?

Asked By: rorocodes

||

Answers:

Your code explicitly performs x = 1 and then x = x + 1 in a loop. As you need the first column in reverse order, and there are n*n numbers to output, instead the first top-left value should be x = n * n and in the first column it should decrease like with x = x - 1. The next column should be filled from end to start, and the next should be filled from start to end, …etc.

I would suggest making an iterator that visits rows in that zig-zag manner: 0, 1, 2, … n – 1, and then n – 1, n – 2, … 0, and back from the start. With that iterator you know exactly to which row you should append the next x value:

# Helper function to generate row numbers in zig-zag order, for as
#   long as needed.
def zigzag(n):
    if n % 2:
        yield from range(n)
    while True:
        yield from range(n - 1, -1, -1)
        yield from range(n)

n = int(input("Enter dimensions of matrix :"))
matrix = [[] for _ in range(n)]
visit = zigzag(n)
for x in range(n*n, 0, -1):
    matrix[next(visit)].append(x)

Then print it:

for row in matrix:
    print(' '.join(map(str, row)))
Answered By: trincot
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.