-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dictionary.cpp
98 lines (79 loc) · 2.32 KB
/
Dictionary.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "Dictionary.hpp"
Dictionary::Dictionary(QObject* parent)
: QObject(parent)
, mState(State::DONE)
{}
int Dictionary::getNewSeed()
{
return ++mSeed;
}
QString Dictionary::getResults() const
{
return mResults;
}
void Dictionary::wipeResults()
{
auto locker = getResultsLocker();
mResults.clear();
}
Dictionary::ResultsLocker Dictionary::getResultsLocker()
{
return ResultsLocker(mResultsMutex);
}
void Dictionary::search(const QString& needle, Dictionary::SearchType type, int seed)
{
QEventLoop loop; // Wait some time before starting
QTimer::singleShot(50, &loop, &QEventLoop::quit);
loop.exec();
if (mSeed.load() != seed)
return; // If seed was reassigned, cancel search
changeState(State::SEARCH);
wipeResults();
if (type == SearchType::QUICK)
this->quickSearch(needle.toStdString(), seed);
else
this->sequenceSearch(needle.toStdString(), seed);
changeState(State::DONE);
}
void Dictionary::changeState(Dictionary::State newState)
{
if(mState != newState) {
mState = newState;
emit stateChanged(newState);
}
}
void Dictionary::addResult(const std::string& result)
{
auto locker = getResultsLocker();
if(!mResults.isEmpty())
mResults.append('\n');
mResults.append(QString::fromStdString(result));
}
void Dictionary::quickSearchPreprocessing(const std::string& needle, int * qsBc) {
int m = static_cast<int>(needle.length());
for (int i = 0; i < ALPHABET_SIZE; ++i)
qsBc[i] = m + 1;
for (int i = 0; i < m; ++i)
qsBc[needle[i]] = m - i;
}
bool Dictionary::quickSearchImplementation(const std::string& needle, const std::string& haystack, const int* qsBc) {
int m = static_cast<int>(needle.length());
int n = static_cast<int>(haystack.length());
for (int j = 0; j <= n - m; j += qsBc[static_cast<unsigned char>(haystack[j + m])])
if (haystack.compare(j, m, needle) == 0)
return true;
return false;
}
bool Dictionary::sequenceSearchImplementation(const std::string& needle, const std::string& haystack)
{
size_t m = needle.length();
if (haystack.length() < m)
return false;
size_t curr = 0;
for(char ch: haystack) {
if (ch == needle[curr])
if (++curr == m)
return true;
}
return false;
}