Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Thursday, May 2, 2013

Nested loops: print pattern (spiral numbers)

Problem: Print the following pattern for a given n (e.g. n=5 below). Number starts at 0 and after reaching 9, it resets to 0.


0 1 2 3 4
5 6 7 8 5
4 3 0 9 6
3 2 1 0 7
2 1 0 9 8


Solution in Python:



def print_pattern(n):
    """


    Author: Mayur P Srivastava
    n is number of colmns or rows.

    """

    matrix = create_matrix(n)

    x0  = -1
    y0  = -1
    num = 0
    
    for m in range(n, 0, -2):
        x0    += 1
        y0    += 1
        x      = 0
        y      = 0
        x_incr = 1
        y_incr = 0

        for i in range((m-1)*4):
            matrix[y+y0][x+x0] = num % 10

            if x+x_incr == m:
                x_incr = 0
                y_incr = 1
            if y+y_incr == m:
                x_incr = -1
                y_incr = 0
            if x+x_incr == -1:
                x_incr = 0
                y_incr = -1

            x   += x_incr
            y   += y_incr
            num += 1

    print "\n".join(" ".join(str(e) for e in row) for row in matrix)


def create_matrix(n, value=0):
    matrix = []
    for i in range(n):
        row = []
        for j in range(n):
            row.append(value)
        matrix.append(row)
    return matrix



Concepts learned: nested loops.

No comments:

Post a Comment