labs-edaf30/lab2/word.cc
2024-11-21 07:48:45 +01:00

61 lines
1.5 KiB
C++

#include "word.h"
#include "dictionary.h"
#include <algorithm>
#include <string>
#include <vector>
using std::string;
using std::vector;
Word::Word(const string &w, const vector<string> &t) : word(w), triagrams(t) {
std::sort(triagrams.begin(), triagrams.end());
}
std::vector<std::string> get_trigrams(const std::string &text) {
std::vector<std::string> trigrams;
if (text.size() < 3) {
return trigrams; // Return an empty vector if the input is too short
}
for (size_t i = 0; i <= text.size() - 3; ++i) {
trigrams.push_back(
text.substr(i, 3)); // Extract a substring of length 3
}
return trigrams;
}
Word::Word(const std::string &w) : word(w) {
this->triagrams = get_trigrams(w);
std::sort(triagrams.begin(), triagrams.end());
}
string Word::get_word() const { return string(); }
unsigned int Word::get_matches(const vector<string> &t) const {
unsigned int matches = 0;
for (const auto &triagram : t) {
if (std::binary_search(triagrams.begin(), triagrams.end(), triagram)) {
++matches;
}
}
return matches;
}
std::ostream &operator<<(std::ostream &out, const Word &w) {
auto space = string(" ");
out << w.word;
out << space;
out << w.triagrams.size();
for (const auto &tria : w.triagrams) {
out << space << tria;
}
return out;
}
bool operator==(const Word &lhs, const Word &rhs) {
return lhs.word == rhs.word &&
std::equal(lhs.triagrams.begin(), lhs.triagrams.end(),
rhs.triagrams.begin());
}