DEV Community

Discussion on: Algorithms Problem Solving: Odd in Matrix

Collapse
 
d33w profile image
d33w

Don't you think there can be a better approach to this problem?

Collapse
 
elcio profile image
Elcio Ferreira

"Better" is a subjective concept. Some could call better this approach:

def odd_cells(n, m, indices):
    matrix = [[0] * m for _ in range(n)]

    for (ri, ci) in indices:
        for col in range(len(matrix[ri])):
            matrix[ri][col] ^= 1

        for row in matrix:
            row[ci] ^= 1

    return sum([sum(line) for line in matrix])

You can say it's better because it's shorter and faster. But it's much harder to read. If I am asked to maintain it, I would prefer much more TK's approach.

Or something like this:

def odd_cells(n, m, indices):
    matrix = init_matrix(n, m)

    for (ri, ci) in indices:
        increment_matrix(matrix, ri, ci)

    return sum_odds(matrix)

def init_matrix(rows, columns):
    return [[0] * columns for _ in range(rows)]

def increment_matrix(matrix, ri, ci):
    for col in range(len(matrix[ri])):
        matrix[ri][col] += 1

    for row in matrix:
        row[ci] += 1

def sum_odds(matrix):
    odds = 0

    for line in matrix:
        odds += sum([(cell % 2) for cell in line])

    return odds

A lot more code, but way easier to read and understand, in my opinion.

Therefore, I ask you the same: don't you think there can be a better approach to this problem? How would you solve it?

Collapse
 
namhle profile image
Nam Hoang Le

I believe that there is a solution use only 4 numbers: number of columns (rows) which have even (odd) cells on each. Need time to test it...