Created
June 5, 2014 18:55
-
-
Save GuillermoPena/1e05a8cf6c4cf42aeeb3 to your computer and use it in GitHub Desktop.
CheckIO - Electronic Station Challenge 4 : Find Sequence
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# CheckIO - Electronic Station Challenge 4 : Find Sequence | |
# http://checkio.org | |
# You are given a matrix of NxN (4≤N≤10). | |
# You should check if there is a sequence of 4 or more matching digits. | |
# The sequence may be positioned horizontally, vertically or diagonally (NW-SE or NE-SW diagonals). | |
# Input: A list of lists. Each list contains integers. | |
# Output: A boolean. Whether or not a sequence exists. | |
# Precondition: 0≤N≤10 ∀ x ∈ matrix : 0 < x < 10 | |
def isSequenceInside(array): | |
i=0 | |
sequence="" | |
while i<len(array): | |
if sequence=="" or str(array[i])==sequence[-1]: | |
sequence+=str(array[i]) | |
if len(sequence)>3: | |
return True | |
else: | |
sequence=str(array[i]) | |
if len(array)-i<4: | |
return False | |
i+=1 | |
def checkio(matrix): | |
# Checking horizontally | |
for row in matrix: | |
if isSequenceInside(row): return True | |
# Checking vertically | |
for index in range(0,len(matrix)): | |
column=[row[index] for row in matrix] | |
if isSequenceInside(column): return True | |
# Checking diagonals | |
for i in range(len(matrix)-3): | |
diagonal1=[matrix[j+i][j] for j in range(len(matrix)-i)] | |
if isSequenceInside(diagonal1): return True | |
diagonal2=[matrix[j][j+i] for j in range(len(matrix)-i)] | |
if diagonal1!=diagonal2 and isSequenceInside(diagonal2): return True | |
diagonal3=[matrix[len(matrix)-1-j-i][j] for j in range(len(matrix)-i)] | |
if isSequenceInside(diagonal3): return True | |
diagonal4=[matrix[len(matrix)-1-j][j+i] for j in range(len(matrix)-i)] | |
if diagonal3!=diagonal4 and isSequenceInside(diagonal4): return True | |
return False | |
#These "asserts" using only for self-checking and not necessary for auto-testing | |
if __name__ == '__main__': | |
assert checkio([ | |
[7, 1, 1, 8, 1, 1], | |
[1, 1, 7, 3, 1, 5], | |
[2, 3, 1, 2, 5, 1], | |
[1, 1, 1, 5, 1, 4], | |
[4, 6, 5, 1, 3, 1], | |
[1, 1, 9, 1, 2, 1] | |
]) == True, "Diagonal" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment