how to traverse though a 2d char array searching for words in java? -


i having trouble school assignment , appreciate insight. asked create wordsearch using 25x25 2d char array , somehow go through array developing algorithm search through find 21 pre-defined words.

so far have been able create ragged array of words need find , 2d array chars placed in each position.

in = new asciidatafile("wordsearch.txt"); display = new asciidisplayer(); int numberwords = in.readint();  wordlist = new char[numberwords][];  (int =0; i<wordlist.length; i++){   wordlist[i] = in.readline().touppercase().tochararray();  } for(int = 0;i<wordlist.length; i++){   display.writeline(" ");   for(int j = 0;j<wordlist[i].length; j++){     display.writechar(wordlist[i][j]);   } } //done wordlists  int gridlength = in.readint(); int gridheight = in.readint();  grid = new char[gridheight][gridlength];  for(int = 0;i<gridlength; i++){   grid[i] = in.readline().tochararray();  } 

my problem in creating algorithm search though 2d array , match character in wordlist. supposed make different methods, searching forwards, backwards , diagonal. have been struggling days forward search.

i how no idea how go problem, far have is

for(int k = 0; k<wordlist.length; k++){   int p = 0;   for(int row = 0;row<gridlength; row++){     for(int col = 0;col<gridheight; col++){        while(p<wordlist[k].length){         if(grid[row][col] == wordlist[k][p]){            //do          }       }     }   } }     

}

any or pointers appreciated!

the trick is, don't need consider 8 possible directions separately. can represent each vector. e.g., 'forward' direction (0, 1) (first row number, column) - vector pointing right. diagonal top-left direction (-1, -1). well, idea.

then, create function

boolean findword(int row, int col, int d_row, int d_col, char[] word); 

it can take current matrix position ((row, col), word supposed start), search direction ((d_row, d_col)) , word for. returns whether given word here.
can invoke different directions, e.g.

findword(row, col, -1, 0, word); findword(row, col, -1, 1, word); findword(row, col, 0, 1, word); ... 

(i'm listing them in clock-wise order)

implementing findword incrementing current position d_row , d_col, until find mismatch in characters or word ends. basic routine this

while (row < total_rows && row >= 0 && col < total_columns && col >= 0) {     // check character here     ...     row += d_row;     col += d_col; } 

i bet you'll have processing code (except input-reading) in 40 lines.


Comments

Popular posts from this blog

java - SNMP4J General Variable Binding Error -

windows - Python Service Installation - "Could not find PythonClass entry" -

Determine if a XmlNode is empty or null in C#? -