HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Word search program

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
wordprogramsearch

Problem

My word search goes through and searches for the first letter in the word slowly. I am looking for a way to optimize the program to search faster and efficiently. I want to find a way to search faster by using a single loop instead of nested loops in my findWords method. I think it would be better to use the appropriate ArrayList from the Hashtable to go only to the row, col coordinates that contain the first letter of the word.

```
public class WordSearch {

VJFrame F;
int dx = 30;
int dy = 30;
int timing = 10;

ArrayList word;

private class Coordinate {
Integer r;
Integer c;

private Coordinate(Integer row, Integer col) {
this.r = row;
this.c = col;
}

}

Hashtable > H = new Hashtable > ();

public WordSearch(VJFrame F) {
this.F = F;
}

public void initialize(String[][] mat, int rows, int cols, String fileName) throws IOException {
BufferedReader buffer = new BufferedReader(new FileReader(fileName));
String s;
for (int i = 0; i ());
}
H.get(mat[i][j]).add(new Coordinate(i, j));
}
}
}

public void display(String[][] mat) {
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
System.out.print(mat[i][j] + " ");
F.add(new JRectangle(dx j, dy i, dx, dy, Color.black, Color.white), timing);
F.add(new JString(dx j + 5, dy i + 25, mat[i][j], Color.black), timing);
}
System.out.println();
F.add(new JString(dx mat[i].length + 5, dy i + 25, Integer.toString(i), Color.white), timing);
}
for (int j = 0; j < mat[0].length; j++) {
F.add(new JString(dx j + 5, dy mat.length + 25, Integer.toString(j), Color.white), timing);
}
}

public boolean match(String[][] matrix, int row, int col, String

Solution

You've asked about how to improve performance, but I would advise you to improve the code organization first. It's rather difficult to do a good job of optimizing the performance with the code in its current form.

Specifically, your code violates the Single-Responsibility Principle, as exemplified in findWords(), which does…

  • Read a file containing a list of words.



  • For each word, display it in yellow, while worrying about laying out that list in a two-column format.



  • Search for the word in the matrix.



  • Highlight rectangles to display the progress as the search progresses.



  • Call displayWord() when the word is found — which sleeps (making benchmarking difficult).



I suggest that you start by ripping out the graphical UI so that you can focus on the algorithm. The algorithm should have a findWord(String word) function that returns a search result in the form of a row coordinate, column coordinate, and a direction.

Once you have that working, then you can go about implementing the UI as a separate class.

Context

StackExchange Code Review Q#112271, answer score: 3

Revisions (0)

No revisions yet.