Monday, November 19, 2018

Q15: Snail shell pattern

Question15: Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

array = [[1,2,3],
         [4,5,6],
         [7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next array consecutively:

array = [[1,2,3],
         [8,9,4],
         [7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
This image will illustrate things more clearly:


NOTE: The 0x0 (empty matrix) is represented as [[]]

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Ah! Mystery solved :P

    #input = [[1,2,3,1], [4,5,6,4], [7,8,9,7], [7,8,9,7]]
    #input = [[1,2,3], [4,5,6], [7,8,9]]
    #input = [[1,2], [3,4], [5,6]]
    #input = [[]]

    tmp = input
    row = len(input[0])
    col = len(input)

    strR = 0
    endR = row-1
    strC = 0
    endC = col-1

    output_list = []
    while (all([val is None for sublist in tmp for val in sublist])) is False:
        for rw in range(0, row):
            if tmp[strR][rw]:
            #print(input[strR][rw], end="")
            output_list.append(input[strR][rw])
            tmp[strR][rw] = None

        for cl in range(0, col):
            if tmp[cl][endR]:
            #print(input[cl][endR], end="")
            output_list.append(input[cl][endR])
            tmp[cl][endR] = None

        for rwr in range(row-1, -1, -1):
            if tmp[endC][rwr]:
            #print(input[endC][rwr], end="")
            output_list.append(input[endC][rwr])
            tmp[endC][rwr] = None

        for clr in range(col-1, -1, -1):
            if tmp[clr][strC]:
            #print(input[clr][strC], end="")
            output_list.append(input[clr][strC])
            tmp[clr][strC] = None

        strR = strR + 1
        endR = endR - 1
        strC = strC + 1
        endC = endC - 1

    print(output_list)

    ReplyDelete