Binary Dictionary Search
in
Programming Questions
•
3 years ago
Hi there.... I'm making a Boggle solver... (just for fun - there's plenty of them around already).
The first step was to write a program where you could just enter the word in a text field and the program would check to see if it is in the dictionary. The dictionary I am using is the SOWPODS official scrabble dictionary which I have as a text file. I decided to use a binary search algorithm - found one on the net and adapted it. I am using G4P for the text field and buttons. The program will just not find any words though. I even replaced the binary search algorithm with a simple sequential one (both are in the program) - still indicates the word is not found. I set up a printwriter to print the word read from the textfield to a file to check nothing weird was happening to it - seemed fine. Well, I'm stumped....
To run this you will need to create a textfile with some words in it, called "sowpods.txt". You will also need the G4P library installed. If you can spot anything obvious that would be great!
- import guicomponents.*;
GTextField wordfield;
GButton findbutton;
PFont arial12;
String[] dictionary;
//PrintWriter output;
void setup()
{
size(500, 200);
background(255);
fill(0);
//output = createWriter("test.txt");
GComponent.globalFont = GFont.getFont(this, "Arial", 13);
dictionary = loadStrings("sowpods.txt");
wordfield = new GTextField(this,"", 10, 26, 200, 30, true);
findbutton = new GButton(this, "Go", 15, 70, 40, 20);
arial12 = loadFont("ArialMT-12.vlw");
textFont(arial12, 12);
}
void draw()
{
}
boolean wordsearch(String word) //the original binary search method
{
int first = 0;
int upto = dictionary.length;
while (first < upto) {
int mid = (first + upto) / 2; // Compute mid point.
if (word.compareTo(dictionary[mid].toLowerCase()) < 0) {
upto = mid; // repeat search in bottom half.
} else if (word.compareTo(dictionary[mid].toLowerCase()) > 0) {
first = mid + 1; // Repeat search in top half.
} else {
return true; // Found it. return true
}
}
return false; // Failed to find key
}
void handleButtonEvents(GButton button)
{
background(255);
if(seqwordsearch(wordfield.viewText().toLowerCase())) text("found", 200, 150);
else text("not found", 200, 150);
text(wordfield.viewText().toLowerCase(),200,175);
//output.println(wordfield.viewText().toLowerCase());
}
void handleTextFieldEvents(GTextField textfield) {}
boolean seqwordsearch(String word) //a slow search method
{
println("word is: " + word);
for(int i=0; i<dictionary.length; i++)
{
println(dictionary[i]);
if(word.equalsIgnoreCase(dictionary[i])) return true;
}
return false;
}
/*
void keyPressed()
{
if(key=='Q')
{
output.flush(); // Writes the remaining data to the file
output.close(); // Finishes the file
exit(); // Stops the program
}
}
*/