Advertisement
Guest User

scrambled.cpp

a guest
Oct 20th, 2012
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. #include<iostream>
  2. #include<fstream>
  3. #include<string>
  4. #include<vector>
  5.  
  6. using namespace std;
  7.  
  8. vector<int> get_letters(const string& word)
  9. {
  10.     vector<int> letters(26, 0);
  11.  
  12.     for(int i=0; i < word.length(); i++)
  13.     {
  14.         letters[word[i] - 'a']++;
  15.     }
  16.    
  17.     return letters;
  18. }
  19.  
  20. bool match(const string& word_a, const string& word_b) //returns true if word_a is an anagram of word_b
  21. {
  22.     vector<int> a = get_letters(word_a);
  23.     vector<int> b = get_letters(word_b);
  24.    
  25.     for(int i=0; i < 26; i++)
  26.     {
  27.         if(a[i] != b[i])
  28.             return false;
  29.     }
  30.    
  31.     return true;
  32. }
  33.  
  34. int main()
  35. {
  36.     ifstream wordlist;     
  37.     wordlist.open("list.txt");
  38.    
  39.     vector<string> list;
  40.    
  41.     while(wordlist.good())
  42.     {
  43.         string word;
  44.         wordlist >> word;
  45.        
  46.         list.push_back(word);
  47.     }
  48.    
  49.     wordlist.close();
  50.    
  51.    
  52.     ifstream scrambled_list;
  53.     scrambled_list.open("scrambled.txt");
  54.    
  55.     vector<string> scrambled;
  56.    
  57.     while(scrambled_list.good())
  58.     {
  59.         string word;
  60.         scrambled_list >> word;
  61.        
  62.         scrambled.push_back(word);
  63.     }
  64.    
  65.     scrambled_list.close();
  66.  
  67.    
  68.     for(vector<string>::iterator list_word = list.begin(); list_word != list.end(); list_word++)
  69.     {      
  70.         for(vector<string>::iterator scrambled_word = scrambled.begin(); scrambled_word != scrambled.end(); scrambled_word++)
  71.         {
  72.             if(match(*list_word, *scrambled_word))
  73.             {
  74.                 cout << *scrambled_word << " -> " << *list_word << endl;
  75.                 //scrambled.erase(scrambled_word); if each scrambled word matches to just one real word
  76.                 break; //remove break if each real word can match to more than one scrambled word
  77.             }
  78.         }
  79.     }
  80.  
  81.    
  82.  
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement