Operating on rows and then on columns of a matrix produces code duplication
- by Chetan
I have the following (Python) code to check if there are any rows or columns that contain the same value:
# Test rows ->
# Check each row for a win
for i in range(self.height): # For each row ...
firstValue = None # Initialize first value placeholder
for j in range(self.width): # For each value in the row
if (j == 0): # If it's the first value ...
firstValue = b[i][j] # Remember it
else: # Otherwise ...
if b[i][j] != firstValue: # If this is not the same as the first value ...
firstValue = None # Reset first value
break # Stop checking this row, there's no win here
if (firstValue != None): # If first value has been set
# First value placeholder now holds the winning player's code
return firstValue # Return it
# Test columns ->
# Check each column for a win
for i in range(self.width): # For each column ...
firstValue = None # Initialize first value placeholder
for j in range(self.height): # For each value in the column
if (j == 0): # If it's the first value ...
firstValue = b[j][i] # Remember it
else: # Otherwise ...
if b[j][i] != firstValue: # If this is not the same as the first value ...
firstValue = None # Reset first value
break # Stop checking this column, there's no win here
if (firstValue != None): # If first value has been set
# First value placeholder now holds the winning player's code
return firstValue # Return it
Clearly, there is a lot of code duplication here. How do I refactor this code?
Thanks!