Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>For rows you can keep a counter, which indicates how many of the same elements in a row you currently have. To do this, iterate through the row and</p> <ul> <li>if current element matches the previous element, increase the counter by one. If counter is 5, then you have found the 5 elements you wanted.</li> <li>if current element doesn't match previous element, set the counter to 1.</li> </ul> <p>The same principle can be applied to columns and diagonals as well. You probably want to use array of counters for columns (one element for each column) and diagonals so you can iterate through the matrix once.</p> <p>I did the small example for a smaller case, but you can easily change it:</p> <pre><code>n = 3 matrix = [[1, 2, 3, 4], [1, 2, 3, 1], [2, 3, 1, 3], [2, 1, 4, 2]] col_counter = [1, 1, 1, 1] for row in range(0, len(matrix)): row_counter = 1 for col in range(0, len(matrix[row])): current_element = matrix[row][col] # check elements in a same row if col &gt; 0: previous_element = matrix[row][col - 1] if current_element == previous_element: row_counter = row_counter + 1 if row_counter == n: print n, 'in a row at:', row, col - n + 1 else: row_counter = 1 # check elements in a same column if row &gt; 0: previous_element = matrix[row - 1][col] if current_element == previous_element: col_counter[col] = col_counter[col] + 1; if col_counter[col] == n: print n, 'in a column at:', row - n + 1, col else: col_counter[col] = 1 </code></pre> <p>I left out diagonals to keep the example short and simple, but for diagonals you can use the same principle as you use on columns. The previous element would be one of the following (depending on the direction of diagonal):</p> <pre><code>matrix[row - 1][col - 1] matrix[row - 1][col + 1] </code></pre> <p>Note that you will need to make a little bit extra effort in the second case. For example traverse the row in the inner loop from right to left.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload