My grade-5 daughter asked help for her home work. In a 10x10 matrix, find 9 country name. I think computer can do better job on this after trying half hour without all the answers. Here is what I did. But it only find 7 countries. The eighth one is England, which is named different in the country list. Where is the last one? Also this script is very inefficient since it searches the country list multiple times with duplicate elements. I found this boggle solver post, which is handling more sophisticate case. It mentioned "trie" data structure can solve this kind of problem efficiently. Can anyone elaborate the details? Thanks in advance,
#!/usr/bin/env python
import numpy as np
import re
import os
B = [['k','l','m','a','l','t','a','l','b','s'],
['i','e','n','y','e','j','i','i','y','r'],
['o','r','o','h','w','d','r','z','u','i'],
['c','o','r','v','m','z','t','a','i','l'],
['i','p','w','b','j','q','s','r','d','a'],
['x','a','a','d','n','c','u','b','f','n'],
['e','g','y','e','h','i','a','h','w','k'],
['m','n','g','a','k','g','f','d','s','a'],
['g','i','d','n','a','l','g','n','e','y'],
['b','s','t','r','f','g','s','a','i','u']]
Matrix=np.matrix(B)
Shape=Matrix.shape
row = Shape[0]-1
col = Shape[1]-1
wordlist = []
DIRECTIONS = [ (-1,-1), (0,-1), (1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
def expand(i,j,xd,yd):
#every time expand to one direction based on passed in variable
if ( i+xd >= 0 and i+xd <= row and j+yd >= 0 and j+yd <= col ):
wordlist.append(wordlist[-1] + Matrix[i+xd,j+yd])
expand(i+xd,j+yd,xd,yd)
print 'matrix is {} x{:2}'.format(Shape[0],Shape[1])
for i in range(Shape[0]):
for j in range(Shape[1]):
for xd,yd in DIRECTIONS:
#before extend to each direction, should set last element as current position letter
# country name is from http://www.countries-list.info/Download-List
wordlist.append(Matrix[i,j])
expand(i,j,xd,yd)
for word in wordlist:
# tried to regex to search file, but it is slow comparing to system grep command
if len(word) > 1 and ( not os.system("grep -iw " + word + " /home/cmaaek/Downloads/list.txt > /dev/null")):
print(word)