Last active
December 21, 2015 13:49
-
-
Save jpmec/6315354 to your computer and use it in GitHub Desktop.
Given the name of a file that contains a list of words and a single word, print the words from the file that are anagrams of the given single word.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <vector> | |
#include <string> | |
#include <algorithm> | |
using namespace std; | |
/// Returns true if word1 is an anagram of word2. | |
bool is_anagram(const string& word1, const string& word2) | |
{ | |
string sorted_word1 = word1; | |
sort(sorted_word1.begin(), sorted_word1.end()); | |
string sorted_word2 = word2; | |
sort(sorted_word2.begin(), sorted_word2.end()); | |
return (sorted_word1 == sorted_word2); | |
} | |
/// Return a list of indices of words that are anagrams of word | |
vector<size_t> get_anagrams(const vector<string>& words, const string& word) | |
{ | |
vector<size_t> result; | |
size_t i = 0; | |
vector<string>::const_iterator iter = words.begin(); | |
for (; iter != words.end(); ++iter, ++i) | |
{ | |
if (is_anagram(*iter, word)) | |
{ | |
result.push_back(i); | |
} | |
} | |
return result; | |
} | |
/// Given the name of a file that contains a list of words and a single word, | |
/// print the words from the file that are anagrams of the given single word. | |
int main(int argc, char* argv[]) | |
{ | |
if (argc != 3) | |
{ | |
cerr << "expected anagram word_list_filename target_word" << endl; | |
return -1; | |
} | |
string filename = argv[1]; | |
string target_word = argv[2]; | |
ifstream list_file(filename.c_str(), std::ifstream::in); | |
vector<string> word_vector; | |
string word; | |
while(getline(list_file, word)) | |
{ | |
word_vector.push_back(word); | |
} | |
vector<size_t> indices = get_anagrams(word_vector, target_word); | |
for (vector<size_t>::iterator i = indices.begin(); i != indices.end(); ++i) | |
{ | |
string anagram = word_vector[*i]; | |
if (anagram != target_word) | |
{ | |
cout << anagram << endl; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment