Search code examples
pythonalgorithmmatrixdata-structurestraversal

Print matrix elements in diamond pattern using python


I need to traverse and print the matrix elements in a diamond pattern.

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

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


Solution

  • # Create a program to print in diamond pattern
    import math;
    matrix = [[ 1,  2,  3,  4,  5], 
              [ 6,  7,  8,  9, 10], 
              [11, 12, 13, 14, 15], 
              [16, 17, 18, 19, 20], 
              [21, 22, 23, 24, 25]]
    
    def printDiamond(matrix):
        round = 0
        # Start with the row and col in the center of the matrix
        row = math.floor(len(matrix) / 2)
        col = math.floor(len(matrix[0]) /2)
        new_list = []
    
        # Subtract number of rows as number of rounds
        # Add one col and add one row - repeat until reaching the center row
        # Subtract one col and add one row - repeat until reaching the center column
        # Subtract one col and subtract one row - repeat until reaching the center row
        # Subtract one row and add one col - repeat until reaching the center column
        movements = {'down_right':[1,1],'down_left':[1,-1],'up_left':[-1,-1],'up_right':[-1,1]}
        directions = [movements['down_right'],movements['down_left'],movements['up_left'],movements['up_right']]
        
        for round in range(len(matrix)):
            # Go upwards first
            new_row = row - round
            new_col = col
            try:
                if new_row >= 0:
                    # Make sure that the indices are 0 or positive
                    #print(matrix[new_row][col])
                    new_list.append(matrix[new_row][col])
            except IndexError:
                # By subtracting round from row to make new row
                # Negative indices will exist
                pass
            for direction in directions:
                # Move in the correct direction 
                # And repeat the number of times equal to the current round
                for pos in range(round):
                    new_row += direction[0]
                    new_col += direction[1]
                    try:
                        if (new_row >= 0 and new_col >= 0):
                            if (matrix[new_row][new_col] not in new_list):
                                new_list.append(matrix[new_row][new_col])
                                # print(matrix[new_row][new_col])
                        
                    except IndexError:
                        pass
        return new_list
    
    new_list = printDiamond(matrix)
    print(new_list)