Skip to content

Instantly share code, notes, and snippets.

@kcuzner
Last active December 21, 2015 05:49
Show Gist options
  • Save kcuzner/6259914 to your computer and use it in GitHub Desktop.
Save kcuzner/6259914 to your computer and use it in GitHub Desktop.
Quick program to find a string inside a grid of letters as if it were a standard word search where words can only go to the right or downward
DGOODDODGOODDO
ODOOGGGDODGOGG
OGOGDOODGOODDD
DGDOOOGGOOGDGO
OGDGOGDGOGGOGD
DDDGDDODOOGDOO
ODGOGGDOOGGOOD
#!/usr/bin/python3
import sys, re
import numpy as np
def main():
# command line options
filename = sys.argv[1] # filename of the grid to search
search = sys.argv[2] # string to find
f = open(filename)
lines = f.readlines()
#left-right
for row in range(len(lines)):
line = lines[row]
result = re.search(search, line)
if result is not None:
print("Found at row " + str(row + 1) + ", column " + str(result.start() + 1) + " east")
return
rline = line[::-1]
result = re.search(search, rline)
if result is not None:
print("Found at row " + str(row + 1) + ", column " + str(result.start() + 1) + " west")
return
#up-down
for col in range(len(lines[0])):
column = ''.join([line[col] for line in lines])
result = re.search(search, column)
if result is not None:
print("Found at column " + str(col + 1) + ", row " + str(result.start() + 1) + " south")
return
rcolumn = column[::-1]
result = re.search(search, rcolumn)
if result is not None:
print("Found at column " + str(col + 1) + ", row " + str(result.start() + 1) + " north")
return
#diagonals...using numpy because its easiest
matrix = np.array([list(l.strip()) for l in lines])
diags = [matrix[::-1,:].diagonal(i) for i in range(-matrix.shape[0]+1,matrix.shape[1])]
diags.extend(matrix.diagonal(i) for i in range(matrix.shape[1]-1,-matrix.shape[0],-1))
diagonals = [''.join(list(n)) for n in diags]
for i in range(len(diagonals)):
line = diagonals[i]
result = re.search(search, line)
if result is not None:
print("Found in diagonal '" + line + "' (index " + str(i) + " of " + str(len(diagonals)) + ")")
return
rline = line[::-1]
result = re.search(search, rline)
if result is not None:
print("Found in diagonal '" + line + "' (reversed) (index " + str(i) + " of " + str(len(diagonals)) + ")")
return
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment