Funny Task To Solve

My friend found and sent me funny task to solve.

Initial idea: There is a city/town represented a matrix, where every digit is a building. Randomly selected building become a post office (random row and column are passed). I have to count all distances from the post office which has 0 distance, to all houses in the town. Distance counted as distance from two closest points.

It was a little bit mind bending, but finaly I came to the next solution:
def generate_matrix(rows, columns):
    return [[0 for column in range(columns)] for row in range(rows)]


def count_distances(matrix, row, column):
    for r_idx, r in enumerate(matrix):
        if r_idx == row-1:
            for c_idx, el in enumerate(r):
                matrix[r_idx][c_idx] = abs(column - c_idx - 1)
        else:
            matrix[r_idx][column-1] = abs(row - r_idx - 1)


    matrix = go_up_left(matrix, row, column)
    matrix = go_up_right(matrix, row, column)
    matrix = go_bottom_left(matrix, row, column)
    matrix = go_bottom_right(matrix, row, column)
    return matrix


def go_up_left(matrix, row, column):
    for r in range(row-2 , -1, -1):
        for c in range(column-2, -1, -1):
            matrix[r][c] = matrix[r+1][c] + matrix[r][c+1]
    return matrix


def go_up_right(matrix, row, column):
    for r in range(row-2 , -1, -1):
        for c in range(column, len(matrix[r])):
            matrix[r][c] = matrix[r+1][c] + matrix[r][c-1]
    return matrix


def go_bottom_left(matrix, row, column):
    for r in range(row, len(matrix)):
        for c in range(column-2, -1, -1):
            matrix[r][c] = matrix[r-1][c] + matrix[r][c+1]
    return matrix


def go_bottom_right(matrix, row, column):
    for r in range(row, len(matrix)):
        for c in range(column, len(matrix[r])):
            matrix[r][c] = matrix[r-1][c] + matrix[r][c-1]
    return matrix


if __name__ == '__main__':
    matrix = count_distances(generate_matrix(6, 16), 3, 4)
    print('\n'.join([''.join(['{:6}'.format(item) for item in row])
      for row in matrix]))


Comments

Popular posts from this blog

Install Kubeflow locally

RabbitMQ and OpenShift