|
-
March 19th, 2007, 05:57 PM
#1
Any way to improve this?
Code:
int main()
{
Graph g;
vector<string> wordList;
ifstream file("words");
if( !file )
{
cerr << "Cannot open dictionary.list " << endl;
return 1;
}
else
{
string word;
if (file.is_open())
{
while (getline (file,word))
{
if (word.size() == 5)
{
wordList.push_back(word);
}
}
file.close();
for (vector<string>::size_type i = 0; i < wordList.size(); ++i)
{
g.addVertex(wordList[i]);
}
for (vector<string>::size_type i = 0; i < wordList.size(); ++i)
{
const string & word1 = wordList[i];
for (vector<string>::size_type j = i+1; j < wordList.size(); ++j)
{
int count = 0;
const string & word2 = wordList[j];
for (int k = 0; k < 5; ++k)
{
if (word1[k] != word2[k])
{
if( ++count > 1) break;
}
}
if (count == 1)
{
g.addEdge(word1, word2, 1);
g.addEdge(word2, word1, 1);
}
}
}
string word1;
string word2;
string again;
do
{
cout << "Please enter a five letter word:";
cin >> word1;
cout << endl << "Please enter another five letter word:";
cin >> word2;
cout << endl;
g.unweighted(word1);
g.printPath(word2);
cout << "Would you like to run this again? (Y or N)";
cin >> again;
}while(again != "N");
}
else
{
cout << "Unable to open file";
return 0;
}
}
}
This code works just fine. It has a list of all 5 letter words, and two words are connected if they can be changed to one or another by a one letter change. The only problem with it is that it takes about 30 seconds to run until it prompts the user for input, which seems like a very long time. The file "words" has a list of almost 400,000 words in it, so maybe there is no way to get around this slowness because of the size of the file and number of compares that have to be performed. Anyone have any ideas on how to improve the performance of this? or is there no way around it?
Last edited by Ehump20; March 19th, 2007 at 05:59 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|