Java Reference
In-Depth Information
1 /**
2 * Routine to read the dictionary.
3 * Error message is printed if dictionary is not sorted.
4 */
5 private void readWords( ) throws IOException
6 {
7 List<String> words = new ArrayList<String>( );
8
9 String lastWord = null;
10 String thisWord;
11
12 while( ( thisWord = wordStream.readLine( ) ) != null )
13 {
14 if( lastWord != null && thisWord.compareTo( lastWord ) < 0 )
15 {
16 System.err.println( "Dictionary is not sorted... skipping" );
17 continue;
18 }
19 words.add( thisWord );
20 lastWord = thisWord;
21 }
22
23 theWords = new String[ words.size( ) ];
24
theWords = words.toArray( theWords );
25 }
figure 10.5
The readWords routine for reading the word list
The code includes an error check to ensure that the word list has been sorted.
Similarly, readPuzzle , shown in Figure 10.6, reads the grid and is also con-
cerned with error handling. We need to be sure that we can handle missing
puzzles, and we want to warn the user if the grid is not rectangular.
The solvePuzzle routine shown in Figure 10.7 nests the row, column, and
direction loops and then calls the private routine solveDirection for each pos-
sibility. The return value is the number of matches found. We give a direction
by indicating a column direction and then a row direction. For instance, south
is indicated by cd=0 and rd=1 and northeast by cd=1 and rd=-1 ; cd can range
from -1 to 1 and rd from -1 to 1 , except that both cannot be 0 simultaneously.
All that remains to be done is to provide solveDirection , which is coded in
Figure 10.8. The solveDirection routine constructs a string by starting at the
base row and column and extending in the appropriate direction.
We also assume that one-letter matches are not allowed (because any one-
letter match would be reported eight times). At lines 14 through 16, we iterate
and extend the string while ensuring that we do not go past the grid's bound-
ary. At line 18 we tack on the next character, using += , and perform a binary
We use two loops
to iterate over the
eight directions.
Search WWH ::




Custom Search