
scrambled.cpp
By: a guest on
Oct 20th, 2012 | syntax:
C++ | size: 1.57 KB | hits: 184 | expires: Never
#include<iostream>
#include<fstream>
#include<string>
#include<vector>
using namespace std;
vector<int> get_letters(const string& word)
{
vector<int> letters(26, 0);
for(int i=0; i < word.length(); i++)
{
letters[word[i] - 'a']++;
}
return letters;
}
bool match(const string& word_a, const string& word_b) //returns true if word_a is an anagram of word_b
{
vector<int> a = get_letters(word_a);
vector<int> b = get_letters(word_b);
for(int i=0; i < 26; i++)
{
if(a[i] != b[i])
return false;
}
return true;
}
int main()
{
ifstream wordlist;
wordlist.open("list.txt");
vector<string> list;
while(wordlist.good())
{
string word;
wordlist >> word;
list.push_back(word);
}
wordlist.close();
ifstream scrambled_list;
scrambled_list.open("scrambled.txt");
vector<string> scrambled;
while(scrambled_list.good())
{
string word;
scrambled_list >> word;
scrambled.push_back(word);
}
scrambled_list.close();
for(vector<string>::iterator list_word = list.begin(); list_word != list.end(); list_word++)
{
for(vector<string>::iterator scrambled_word = scrambled.begin(); scrambled_word != scrambled.end(); scrambled_word++)
{
if(match(*list_word, *scrambled_word))
{
cout << *scrambled_word << " -> " << *list_word << endl;
//scrambled.erase(scrambled_word); if each scrambled word matches to just one real word
break; //remove break if each real word can match to more than one scrambled word
}
}
}
return 0;
}