Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Clear category for Find Sequence by Piotr.Helminiak
import itertools
def check(matrix, value, togo, seq):
while togo:
i=togo.pop()
if matrix[i[0]][i[1]]==value:
seq+=1
if seq==4:
return True
else:
return False
return False
def lines(y, x, size):
horizontal=[(y,x+i) for i in range(1,size-x)]
vertical=[(y+i,x) for i in range(1,size-y)]
diagonal_1=[(y+i,x+i) for i in range(1,size) if y+1 in range(1,size-1) and x+i in range(1,size)]
diagonal_2=[(y+i,x-i) for i in range(1,size) if y+1 in range(1,size-1) and x-i in range(0,size)]
horizontal.reverse()
vertical.reverse()
diagonal_1.reverse()
diagonal_2.reverse()
return horizontal,vertical,diagonal_1,diagonal_2
def checkio(matrix):
size = len(matrix)
tocheck=list(itertools.product((l for l in range(0,size)),(w for w in range(0,size))))
tocheck.reverse()
while tocheck:
now_y, now_x=tocheck.pop()
value=matrix[now_y][now_x]
seq=1
togo_h,togo_v,togo_d1,togo_d2=lines(now_y,now_x,size)
if check(matrix,value,togo_h,seq) or check(matrix,value,togo_v,seq) or check(matrix,value,togo_d1,seq) or check(matrix,value,togo_d2,seq):
return True
return False
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert checkio([
[1, 2, 1, 1],
[1, 1, 4, 1],
[1, 3, 1, 6],
[1, 7, 2, 5]
]) == True, "Vertical"
assert checkio([
[7, 1, 4, 1],
[1, 2, 5, 2],
[3, 4, 1, 3],
[1, 1, 8, 1]
]) == False, "Nothing here"
assert checkio([
[2, 1, 1, 6, 1],
[1, 3, 2, 1, 1],
[4, 1, 1, 3, 1],
[5, 5, 5, 5, 5],
[1, 1, 3, 1, 1]
]) == True, "Long Horizontal"
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"
Nov. 11, 2016