Created
December 9, 2011 07:41
-
-
Save s3thi/1450643 to your computer and use it in GitHub Desktop.
Python QOTW #1 in C++
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 <algorithm> | |
#include <fstream> | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
bool can_make(string word, vector<char> letters); | |
int get_max_len(vector<string> words); | |
int main(int argc, char* argv[]) | |
{ | |
// Grab the dictionary. | |
fstream dict_file(argv[1]); | |
string in; | |
vector<string> dict_words; | |
while(getline(dict_file, in)) dict_words.push_back(in); | |
dict_file.close(); | |
// Get the list of input letters. | |
vector<char> letters; | |
for (int i = 2; i < argc; i++) | |
letters.push_back(argv[i][0]); | |
// Get all words. | |
vector<string> all_words; | |
vector<string>::iterator it; | |
for (it = dict_words.begin(); it < dict_words.end(); it++) | |
if (can_make(*it, letters)) | |
all_words.push_back(*it); | |
// Get longest words. | |
int max_len = get_max_len(all_words); | |
vector<string> longest_words; | |
for (it = all_words.begin(); it < all_words.end(); it++) | |
if ((*it).length() == max_len) | |
longest_words.push_back(*it); | |
// Print the result. | |
for (it = longest_words.begin(); it < longest_words.end(); it++) | |
cout << *it << " "; | |
cout << endl; | |
return 0; | |
} | |
bool can_make(string word, vector<char> letters) | |
{ | |
/* | |
Return true if the word <word> can be generated by all letters in <letters> | |
and only the letters in <letters>. | |
*/ | |
if (word.length() > letters.size()) return false; | |
vector<char> l(letters); | |
vector<char> word_letters(word.c_str(), word.c_str()+word.length()); | |
vector<char>::iterator it, loc; | |
// Iterate through <word_letters>. If a letter in <word_letters> also | |
// appears in <letters>, remove it. Otherwise, return false. | |
for (it = word_letters.begin(); it < word_letters.end(); it++) { | |
loc = find(letters.begin(), letters.end(), *it); | |
if (loc == letters.end()) return false; | |
letters.erase(loc); | |
} | |
return true; | |
} | |
int get_max_len(vector<string> words) | |
{ | |
/* | |
Return the length of the longest word(s) in <words>. | |
*/ | |
int max_len = 0; | |
vector<string>::iterator it; | |
for (it = words.begin(); it < words.end(); it++) | |
if ((*it).length() > max_len) | |
max_len = (*it).length(); | |
return max_len; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment