I am trying to make a program which takes a text file with words and letters with which it outputs the longest word it can create with the letters you provided.
This is the code:
#include <algorithm>
#include <fstream>
#include <iostream>
#include <unordered_set>
#include <cstring>
#include <chrono>
using namespace std;
using namespace std::chrono;
bool can_make (string word, unordered_set<char> letters);
int main (int argc, char* argv[]) {
fstream dict_file(argv[1]);
unordered_set<char> letters;
unordered_set<string> words;
string word;
size_t max_len = 0;
for (int i = 2; i < argc; i++) {
for (int j = 0; j < strlen(argv[i]); j++) {
letters.insert(argv[i][j]);
}
}
while (getline(dict_file, word)) {
if (word.length() > max_len && can_make(word, letters)) {
words.clear();
max_len = word.length();
words.insert(word);
} else if (word.length() == max_len && can_make(word, letters)) {
words.insert(word);
}
}
dict_file.close();
auto start = high_resolution_clock::now();
cout << "Words: ";
for (string word : words) {
cout << word << " ";
}
cout << "\n" << endl;
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time elapsed: " << (duration.count()) << " microseconds" << endl;
cout << endl;
return 0;
}
bool sort_func (string first, string second) {
return first.length() > second.length();
}
bool can_make (string word, unordered_set<char> l) {
for (char i : word) {
if (l.find(i) == l.end()) return false;
}
return true;
}
I want to make the code as fast as possible, and the only thing that is taking a long time is the file reading. Is there a way to read a file faster?