Advertisement
aaronvan

wordChain

Feb 11th, 2019
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.80 KB | None | 0 0
  1. void wordChain(string file, string startWord) {
  2.     map<string, string> first2Letters;
  3.     vector<string> dictionary;
  4.     string word;
  5.     ifstream inputFile(file);
  6.     if (inputFile) {
  7.         while (inputFile >> word) {
  8.             string firstTwo = word.substr(0, 2);
  9.             first2Letters.insert(pair<string, string> {firstTwo, word});
  10.             dictionary.push_back(word);
  11.         }
  12.     }
  13.     inputFile.close();
  14.     cout << startWord << endl; 
  15.     for (auto w : dictionary) {
  16.         string lastTwo = startWord.substr(startWord.length() - 2);
  17.         map<string, string>::iterator iter;
  18.         iter = first2Letters.find(lastTwo);
  19.         if (iter != first2Letters.end()) {
  20.             string toRemove = startWord;
  21.             dictionary.erase(remove(dictionary.begin(), dictionary.end(), toRemove), dictionary.end());
  22.             startWord = first2Letters[lastTwo];
  23.             cout << startWord << endl;
  24.         }
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement