-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbin-search.cc
92 lines (76 loc) · 2.74 KB
/
bin-search.cc
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
#include <iostream>
#include "../include/index.hpp"
using namespace std;
jay_io::Index returnIndexObjAtByte_InStream_(int offset, std::fstream *fs)
{
bool isExtracted = false;
std::string extr;
char c = 0;
int i = offset;
while (!isExtracted) {
(*fs).get(c);
(*fs).clear();
if (c == '\n') {
std::getline(*fs, extr, '\n');
(*fs).clear();
isExtracted = true;
}
else {
i--;
(*fs).seekg(i);
}
}
return jay_io::Index(extr);
}
jay_io::Index binarySearchDataPOS(std::string query, std::string filepath)
{
std::fstream file(filepath, std::ios::in);
auto returnFinalByteOffset = [] (std::fstream* f) -> std::streamoff {
(*f).seekg(0, std::ios::end);
std::streamoff pos = (*f).tellg();
(*f).seekg(0);
return pos;
};
auto findStartByteOfIndexPOS = [] (std::fstream* f) -> std::streamoff {
std::string s;
std::streamoff tempOffset, startOffset;
bool isStartByteFound = false;
(*f).seekg(0);
while (!isStartByteFound) {
std::streamoff tempOffset = (*f).tellg();
std::getline(*f, s, '\n');
(*f).clear();
if (s[0] == ' ' && s[1] == ' ')
continue;
else {
isStartByteFound = true;
startOffset = tempOffset;
}
}
(*f).seekg(0);
cout << startOffset;
return startOffset;
};
bool isEntryFound = false;
jay_io::Index t, i;
std::streamoff mean, start = findStartByteOfIndexPOS(&file), stop = returnFinalByteOffset(&file);
while (!isEntryFound) {
mean = (start + stop)/2;
i = returnIndexObjAtByte_InStream_(mean, &file);
i.previewIndex();
int diff = strcmp(i.lemma.c_str(), query.c_str());
if (diff < 0)
start = mean;
else if (diff > 0)
stop = mean;
else /* if (diff == 0) */ {
t = i;
isEntryFound = true;
}
}
return t;
}
int main() {
jay_io::Index x = binarySearchDataPOS("act", "../wndb3/index/index.noun");
x.previewIndex();
}