-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrepl.cpp
More file actions
1462 lines (1271 loc) · 49.9 KB
/
repl.cpp
File metadata and controls
1462 lines (1271 loc) · 49.9 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Authors
// Maksims Uhanovs, 201RDB140
// Aleksandrs Samsonovičs, 201RDB124
// Kirils Trofimovs, 201RDB175
// g++ -std=c++17 -o repl repl.cpp -lstdc++fs
#include <iostream>
#include <experimental/filesystem>
#include <string>
#include <map>
#include <sstream>
#include <vector>
#include <iterator>
#include <unordered_map>
#include <iomanip>
#include <set>
#include <algorithm>
#include <fstream>
// In the better times would be better to implement builder pattern
class Config {
public:
Config() = default;
~Config() = default;
Config(const Config &other) = default;
enum Detector {
JaccardIndex,
Moss
};
[[nodiscard]] const std::experimental::filesystem::path &getResultPath() const {
return resultPath;
}
void setResultPath(std::experimental::filesystem::path path) {
resultPath = std::move(path);
pagesPath = resultPath / std::experimental::filesystem::path("pages");
}
[[nodiscard]] const std::experimental::filesystem::path &getPagesPath() const {
return pagesPath;
}
[[nodiscard]] const std::string &getRed() const {
return red;
}
void setRed(const std::string &red) {
validateColorHexString(red);
Config::red = red;
}
[[nodiscard]] const std::string &getYellow() const {
return yellow;
}
void setYellow(const std::string &yellow) {
validateColorHexString(yellow);
Config::yellow = yellow;
}
[[nodiscard]] const std::string &getGreen() const {
return green;
}
void setGreen(const std::string &green) {
validateColorHexString(green);
Config::green = green;
}
[[nodiscard]] const std::string &getGray() const {
return gray;
}
void setGray(const std::string &gray) {
validateColorHexString(gray);
Config::gray = gray;
}
const std::string &getCodeColorMark() const {
return codeColorMark;
}
void setCodeColorMark(const std::string &codeMark) {
validateColorHexString(codeMark);
Config::codeColorMark = codeMark;
}
int getThresholdGreen() const {
return thresholdGreen;
}
void setThresholdGreen(int thresholdGreen) {
if (thresholdGreen > 100 || thresholdGreen < 0) {
throw std::runtime_error("thresholdGreen should be in the range 0 < thresholdGreen < 100!");
}
Config::thresholdGreen = thresholdGreen;
}
int getThresholdYellow() const {
return thresholdYellow;
}
void setThresholdYellow(int thresholdYellow) {
if (thresholdYellow > 100 || thresholdYellow < thresholdGreen) {
throw std::runtime_error("thresholdYellow should be in the range thresholdGreen < thresholdYellow < 100!");
}
Config::thresholdYellow = thresholdYellow;
}
int getAbbrInRow() const {
return abbrInRow;
}
void setAbbrInRow(int abbrInRow) {
if (abbrInRow < 1) {
throw std::runtime_error("abbrInRow cannot be less than 1!");
}
Config::abbrInRow = abbrInRow;
}
int getHighlightingThreshold() const {
return highlightingThreshold;
}
void setHighlightingThreshold(int highlightingThreshold) {
if (highlightingThreshold < 1) {
throw std::runtime_error("highlightingThreshold cannot be less than 1!");
}
Config::highlightingThreshold = highlightingThreshold;
}
[[nodiscard]] Detector getDetectorType() const {
return detectorType;
}
void setDetectorType(Detector detectorType) {
Config::detectorType = detectorType;
}
int getJaccardWindow() const {
return jaccardWindow;
}
void setJaccardWindow(int jaccardWindow) {
if (jaccardWindow < 2) {
throw std::runtime_error("Window width cannot be less than 2!");
}
Config::jaccardWindow = jaccardWindow;
}
const std::pair<int, int> &getMossWindow() const {
return mossWindow;
}
void setMossWindow(const std::pair<int, int> &mossWindow) {
if (mossWindow.first < 2) {
throw std::runtime_error("Window width cannot be less than 2!");
}
if (mossWindow.second < 2) {
throw std::runtime_error("Hash width cannot be less than 2!");
}
Config::mossWindow = mossWindow;
}
private:
std::experimental::filesystem::path resultPath = std::experimental::filesystem::path("results");
std::experimental::filesystem::path pagesPath = resultPath / std::experimental::filesystem::path("pages");
std::string red = "#FF241C";
std::string yellow = "#F5EF35";
std::string green = "#4EF52C";
std::string gray = "#B1A9A3";
std::string codeColorMark = "#FF6F9D";
int thresholdGreen = 40; // threshold by which files are decided to be fine.
int thresholdYellow = 60; // threshold value which is thresholdGreen < value < thresholdYellow
int abbrInRow = 6; // number of files in the legend table
int highlightingThreshold = 3; // how many tokens should be equal to start highlighting the line
Detector detectorType = Detector::JaccardIndex; // Which detector to use. Differs approach of showing the data
int jaccardWindow = 5; // default window for Jaccard detector
std::pair<int, int> mossWindow = {4, 3}; // 1. window width 2. hash width
// for the color code check
std::map<char, char> allowedHexSymbols = {
{'0', 0},
{'1', 1},
{'2', 2},
{'3', 3},
{'4', 4},
{'5', 6},
{'6', 6},
{'7', 7},
{'8', 8},
{'9', 9},
{'A', 10},
{'B', 11},
{'C', 12},
{'D', 13},
{'E', 14},
{'F', 15}
};
void validateColorHexString(const std::string &color) {
if (color.size() != 7) {
throw std::runtime_error("Length of the color should be 6!");
}
if (color[0] != '#') {
throw std::runtime_error("Color hex should start with #");
}
for (int i = 1; i < color.size(); ++i) {
if (allowedHexSymbols.find(color[i]) == allowedHexSymbols.end()) {
throw std::runtime_error("Incorrect hex symol was used!");
}
}
}
};
class File {
public:
explicit File(const std::experimental::filesystem::path &path) {
read(path);
}
[[nodiscard]] std::vector<std::string> &getData() {
return data;
}
private:
void read(const std::experimental::filesystem::path &path) {
std::ifstream input(path);
std::stringstream buffer;
buffer << input.rdbuf();
std::string rawString = buffer.str();
auto result = clearComments(rawString);
splitToDataVector(result);
}
void splitToDataVector(std::string &str) {
std::string delimiter = "\n";
size_t pos;
std::string token;
while ((pos = str.find(delimiter)) != std::string::npos) {
token = str.substr(0, pos);
data.push_back(token);
str.erase(0, pos + delimiter.length());
}
// push last line
data.push_back(str);
}
static std::string clearComments(std::string &rawString) {
std::stringstream result;
bool skipOneLine = false;
bool skipMultiLine = false;
bool pushToBuf = true;
for (int i = 0; i < rawString.size() - 1; ++i) {
if (rawString[i] == '/' && rawString[i + 1] == '/' && !skipMultiLine) {
skipOneLine = true;
pushToBuf = false;
}
if (skipOneLine && rawString[i] == '\n') {
skipOneLine = false;
pushToBuf = true;
}
if (rawString[i] == '/' && rawString[i + 1] == '*') {
pushToBuf = false;
skipMultiLine = true;
}
if (rawString[i] == '*' && rawString[i + 1] == '/') {
pushToBuf = true;
skipMultiLine = false;
// skip end comment symbols
i += 2;
// check for file end
if (i >= rawString.size()) break;
}
if (pushToBuf) {
result << rawString[i];
}
}
return result.str();
}
std::vector<std::string> data;
};
struct page {
std::map<unsigned int, unsigned int> first;
std::map<unsigned int, unsigned int> second;
};
class HtmlOutput {
public:
explicit HtmlOutput(const Config &config) : config(config) {
std::experimental::filesystem::create_directory(config.getResultPath());
std::experimental::filesystem::create_directory(config.getPagesPath());
}
void outputHtml(const std::vector<std::vector<double>> &table,
const std::vector<std::experimental::filesystem::path> &files,
const std::vector<page> &highlightedLines) {
for (int i = 0; i < files.size(); ++i) {
for (int j = 0; j < files.size(); ++j) {
if (i == j) continue;
unsigned int index = i * files.size() + j;
outputComparisonPage(files[i], files[j], highlightedLines[index]);
}
}
std::string html = createResultTable(table, files);
std::ofstream output(config.getResultPath() / "result.html");
output << html;
output.close();
}
void outputComparisonPage(const std::experimental::filesystem::path &firstFile, const std::experimental::filesystem::path &secondFile,
const page &comparisonPage) {
std::string html = createComparisonPage(firstFile, secondFile, comparisonPage);
std::ofstream output(config.getPagesPath() / pageName(firstFile, secondFile));
output << html;
output.close();
}
private:
Config config;
[[nodiscard]] static std::string pageName(const std::experimental::filesystem::path &firstFile, const std::experimental::filesystem::path &secondFile) {
std::stringstream filename;
filename << firstFile.stem().string() << "-" << secondFile.stem().string() << ".html";
return filename.str();
}
[[nodiscard]] std::vector<std::string> readSourceCode(const std::experimental::filesystem::path &path, const page &comparisonPage,
unsigned int whichFileToCompare) {
std::map<unsigned int, unsigned int> highlightedLines;
if (whichFileToCompare == 1) {
highlightedLines = comparisonPage.first;
} else if (whichFileToCompare == 2) {
highlightedLines = comparisonPage.second;
}
// It is easier to use vector since
// code highlighting depends on the line number
std::vector<std::string> codeLines;
File input(path);
auto &inputVec = input.getData();
std::stringstream codeLine;
unsigned int lineNumber = 1;
for (auto &line : inputVec) {
auto pos = line.find('<');
if (pos != std::string::npos) {
line.replace(pos, 1, "<");
}
pos = line.find('>');
if (pos != std::string::npos) {
line.replace(pos, 1, ">");
}
if (config.getDetectorType() != Config::Detector::Moss &&
highlightedLines.find(lineNumber) != highlightedLines.end() &&
highlightedLines[lineNumber] > config.getHighlightingThreshold()) {
codeLine << "<code style='background-color:" << config.getCodeColorMark()
<< "'>" << line << "</code>\n";
} else {
codeLine << "<code>" << line << "</code>\n";
}
codeLines.push_back(codeLine.str());
codeLine.str("");
lineNumber++;
}
return codeLines;
}
[[nodiscard]] std::string createComparisonPage(const std::experimental::filesystem::path &firstFile, const std::experimental::filesystem::path &secondFile,
const page &comparisonPage) {
std::stringstream body;
body <<
"<!DOCTYPE html>"
"<html lang='en'>"
"<head>"
"<meta charset='UTF-8'>"
"<title>" << firstFile.filename().string() << " vs " << secondFile.filename().string() <<
"</title>"
"<style>"
"code {"
"font-family: 'Courier New', Courier, monospace;"
"}"
".container {"
"display: grid;"
"grid-template-columns: 1fr 1fr;"
"grid-gap: 20px;"
"}"
"pre.code {"
"white-space: pre-wrap;"
"}"
"pre.code::before {"
"counter-reset: listing;"
"}"
"pre.code code {"
"counter-increment: listing;"
"}"
"pre.code code::before {"
"content: counter(listing) '. ';"
"display: inline-block;"
"width: 8em;"
"padding-left: auto;"
"margin-left: auto;"
"text-align: right;"
"}"
"</style>"
"</head>"
"<body>"
"<div class='container'>"
"<div class='source'>"
"<h3>Filename: " << firstFile.filename().string() <<
"</h3>"
"<pre class='code'>";
auto firstSourceCode = readSourceCode(firstFile, comparisonPage, 1);
for (const auto &line: firstSourceCode) {
body << line;
}
body << "</pre>";
// closing source div
body << "</div>";
body <<
"<div class='source'>"
"<h3>Filename: " << secondFile.filename().string() <<
"</h3>"
"<pre class='code'>";
auto secondSourceCode = readSourceCode(secondFile, comparisonPage, 2);
for (const auto &line: secondSourceCode) {
body << line;
}
body << "</pre>";
// closing source div
body << "</div>";
// closing container div
body << "</div>";
body << "</body>";
body << "</html>";
return body.str();
}
[[nodiscard]] std::string createResultTable(const std::vector<std::vector<double>> &table,
const std::vector<std::experimental::filesystem::path> &files) const {
std::stringstream body;
body <<
"<!DOCTYPE html>"
"<html lang='en'>"
"<head>"
"<meta charset='UTF-8'>"
"<title>Check results</title>"
"<style>"
"h1 {"
"text-align: center;"
"}"
".green {"
"background-color: " << config.getGreen() <<
"}"
".red {"
"background-color: " << config.getRed() <<
"}"
".yellow {"
"background-color: " << config.getYellow() <<
"}"
".gray {"
"background-color: " << config.getGray() <<
"}"
"table {"
"margin: 0 auto;"
"width: 40%;"
"text-align: center;"
"}"
"table, th, td {"
"border: 1px solid black;"
"padding: 4px;"
"}"
"a {"
"color: black;"
"}"
"</style>"
"</head>"
"<body>"
"<h1>Plagiarism check results: </h1>"
"<table>";
for (int i = 0; i < table.size() + 1; ++i) {
body << "<tr>";
for (int j = 0; j < table[0].size() + 1; ++j) {
// first row
if (i == 0) {
if (j == 0) {
body << "<th></th>";
continue;
}
body << "<th>" << j << "</th>";
continue;
}
// next rows
// ------------
// first column
if (j == 0) {
body << "<th>" << i << "</th>";
continue;
}
// gray out diagonal
if (j == i) {
body << "<td class=gray></td>";
continue;
}
auto value = table[i - 1][j - 1];
if (value > 100) value = 100;
std::string classColor;
if (value < config.getThresholdGreen()) {
classColor = "green";
} else if (value < config.getThresholdYellow()) {
classColor = "yellow";
} else {
classColor = "red";
}
if (config.getDetectorType() == Config::Detector::Moss) {
body << "<td class=" << classColor << ">" <<
std::fixed << std::setprecision(1) <<
value << "</td>";
} else {
body << "<td class=" << classColor << ">" <<
"<a href=pages/" <<
pageName(files[i - 1], files[j - 1]) <<
">" << std::fixed << std::setprecision(1) <<
value << "%</a>" << "</td>";
}
}
body << "</tr>";
}
// Result table is created
body << "</table>";
// Starting the creation of abbreviation table
body << "<h1>Abbreviation</h1>";
body << "<table>";
int fileCountInRow = config.getAbbrInRow();
for (int i = 0; i < files.size(); ++i) {
if (i % fileCountInRow == 0) {
body << "<tr>";
}
body << "<th>" << i + 1 << ": " << "</th>";
std::string filename = files[i].filename().string();
body << "<td>" << "<a href=" << files[i].string() << ">" <<
filename << "</a></td>";
if (i % fileCountInRow == fileCountInRow - 1) {
body << "</tr>";
}
}
body << "</table>";
body << "</body>";
body << "</html>";
return body.str();
}
};
class JaccardIndex {
public:
std::unordered_map<unsigned int, std::vector<std::pair<int, int>>> map;
std::vector<std::vector<std::vector<int>>> t; // temporary table with results and file indices
std::vector<std::vector<double>> res;
std::vector<int> fsize; // files sizes
std::vector<std::vector<unsigned int>> tokenLines;
std::vector<page> highlightedLines;
int width; // window width
explicit JaccardIndex(int width) : width(width) {}
[[nodiscard]] unsigned int hashed(std::vector<unsigned int> const &vec) const {
std::size_t seed = vec.size();
for (auto &i : vec) {
seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
void nextFile(const std::vector<unsigned int> &input, const std::vector<unsigned int> &lines) {
tokenLines.emplace_back();
for (int i = 0; i < input.size() - width + 1; ++i) {
tokenLines[tokenLines.size() - 1].push_back(lines[i]);
std::vector<unsigned int> toBeHashed(input.begin() + i, input.begin() + i + width);
auto hash = hashed(toBeHashed);
if (map.find(hash) == map.end()) {
map[hash] = std::vector<std::pair<int, int>>();
}
map[hash].push_back(std::pair(fsize.size(), i));
}
fsize.push_back(input.size());
}
std::vector<std::vector<double>> run() {
for (int i = 0; i < fsize.size(); ++i) {
t.emplace_back();
res.emplace_back();
for (int j = 0; j < fsize.size(); ++j) {
t[i].emplace_back();
res[i].push_back(0);
}
}
filesIntoTable();
sortResults();
calculateResults();
return res;
}
void printResults() {
for (int i = 0; i < fsize.size(); ++i) {
std::cout << " " << i << " ";
}
std::cout << std::endl;
for (int i = 0; i < fsize.size(); ++i) {
std::cout << i;
for (int j = 0; j < fsize.size(); ++j) {
if (i == j) {
std::cout << " ";
} else {
printf("%7.2f", res[i][j]);
}
}
std::cout << std::endl;
}
}
std::vector<page> returnLines() {
for (int i = 0; i < fsize.size(); i++) {
for (int j = 0; j < fsize.size(); j++) {
highlightedLines.emplace_back();
if (i == j) {
continue;
}
for (int l = 0; l < t[i][j].size(); l++) {
for (int q = 0; q < width; q++) {
auto &lineOccur = highlightedLines[highlightedLines.size() - 1].first;
if (lineOccur.find(tokenLines[i][t[i][j][l]] + q) == lineOccur.end()) {
lineOccur[tokenLines[i][t[i][j][l]] + q] = 0;
}
lineOccur[tokenLines[i][t[i][j][l]] + q]++;
}
}
for (int l = 0; l < t[j][i].size(); l++) {
for (int q = 0; q < width; q++) {
auto &lineOccur = highlightedLines[highlightedLines.size() - 1].second;
if (lineOccur.find(tokenLines[j][t[j][i][l]] + q) == lineOccur.end()) {
lineOccur[tokenLines[j][t[j][i][l]] + q] = 0;
}
lineOccur[tokenLines[j][t[j][i][l]] + q]++;
}
}
}
}
return highlightedLines;
}
private:
void filesIntoTable() {
for (const auto &p : map) {
std::vector<int> c(fsize.size(), 0);
for (int i = 0; i < p.second.size(); ++i) {
c[p.second[i].first] = 1;
}
std::vector<int> d;
for (int i = 0; i < fsize.size(); i++) {
if (c[i] == 1) {
d.push_back(i);
}
}
for (int i = 0; i < p.second.size(); i++) {
for (int j = 0; j < d.size(); j++) {
t[p.second[i].first][d[j]].push_back(p.second[i].second);
}
}
}
}
void countingSort(std::vector<int> &v) {
int m = -1;
for (const auto &elem : v) {
if (elem > m) {
m = elem;
}
}
std::vector<int> e(m + 1, 0);
for (const auto &elem : v) {
e[elem]++;
}
int c = 0;
for (int i = 0; i < m + 1; i++) {
for (int j = 0; j < e[i]; j++) {
v[c] = i;
c++;
}
}
}
void sortResults() {
for (int i = 0; i < fsize.size(); i++) {
for (int j = 0; j < fsize.size(); j++) {
countingSort(t[i][j]);
}
}
}
void calculateResults() {
for (int i = 0; i < fsize.size(); ++i) {
for (int j = 0; j < fsize.size(); ++j) {
if (t[i][j].size() > 0) {
res[i][j] += width;
}
for (int l = 1; l < t[i][j].size(); ++l) {
if (t[i][j][l] - t[i][j][l - 1] < width) {
res[i][j] += (t[i][j][l] - t[i][j][l - 1]);
} else {
res[i][j] += width;
}
}
res[i][j] = res[i][j] / (fsize[i] + fsize[j] - res[i][j]) * 100;
}
}
}
};
class Moss {
public:
std::unordered_map<unsigned int, std::vector<int>> map;
std::vector<std::vector<unsigned int>> fingers;
std::vector<std::vector<double>> res;
int k, w; // k-grams, winnowing
Moss(int k, int w) : k(k), w(w) {}
std::size_t hashed(std::vector<unsigned int> const &vec) const {
std::size_t seed = vec.size();
for (auto &i : vec) {
seed ^= i + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
return seed;
}
void nextFile(const std::vector<unsigned int> &input) {
fingers.emplace_back();
std::vector<unsigned int> hashes;
hashes.reserve(input.size() - k + 1);
for (int i = 0; i < input.size() - k + 1; ++i) {
std::vector<unsigned int> toBeHashed(input.begin() + i, input.begin() + i + k);
auto hash = hashed(toBeHashed);
hashes.push_back(hash);
}
for (int i = 0; i < hashes.size() - w + 1; ++i) {
unsigned int minValue = hashes[i];
int minIndex = i;
for (int j = i; j < i + w; ++j) {
if (hashes[j] < minValue) {
minValue = hashes[j];
minIndex = j;
}
}
i = minIndex;
fingers[fingers.size() - 1].push_back(minValue);
}
}
void fingerprintsToHashmap() {
for (int i = 0; i < fingers.size(); ++i) {
for (int j = 0; j < fingers[i].size(); ++j) {
if (map.find(fingers[i][j]) == map.end()) {
map[fingers[i][j]] = std::vector<int>();
}
map[fingers[i][j]].push_back(i);
}
}
}
void hashmapToTable() {
for (const auto &p : map) {
std::vector<int> c(fingers.size(), 0);
for (int i = 0; i < p.second.size(); ++i) {
c[p.second[i]] = 1;
}
std::vector<int> d;
for (int i = 0; i < c.size(); ++i) {
if (c[i] == 1) {
d.push_back(i);
}
}
for (int i = 0; i < p.second.size(); ++i) {
for (int j = 0; j < d.size(); ++j) {
res[p.second[i]][d[j]]++;
}
}
}
}
void calculateResults() {
for (int i = 0; i < res.size(); ++i) {
for (int j = 0; j < res[i].size(); ++j) {
res[i][j] = (double) (res[i][j] / fingers[i].size()) * 100;
}
}
}
std::vector<std::vector<double>> run() {
for (int i = 0; i < fingers.size(); ++i) {
res.emplace_back();
for (int j = 0; j < fingers.size(); ++j) {
res[i].push_back(0);
}
}
fingerprintsToHashmap();
hashmapToTable();
calculateResults();
return res;
}
};
static int freeTokenId = 100;
class Tokenizer {
public:
class Token {
public:
Token(int position_, int tokenId_) : position(position_), id(tokenId_) {
if (reverseTokenMap.count(tokenId_) > 0)
value = reverseTokenMap[tokenId_];
}
Token(int position_, const std::string &value_) : position(position_), value(value_) {
if (tokenMap.count(value_) > 0)
id = tokenMap[value];
}
int getPosition() const {
return position;
}
int getId() const {
return id;
}
const std::string &getValue() const {
return value;
}
private:
int position = -1;
int id = -1;
std::string value = "invalid";
};
explicit Tokenizer(const std::vector<std::string> &inputStrings_) : inputStrings(inputStrings_) {}
static std::vector<std::string> splitData(const std::string &data) {
static const std::set<char> splitters = {
'{', '}', '(', ')', '\"', '+', '-', '/', '*', '%', '=', '!',
'<', '>', '?', ':', '&', '|', '^', '~', '[', ']', ',', '.', ';'
};
std::vector<std::string> result;
std::string token;
for (const auto &c : data) {
if (splitters.count(c) > 0) {
if (!token.empty())
result.push_back(token);
result.push_back({c});
token = "";
} else {
token += c;
}
}
if (!token.empty())
result.push_back(token);
return result;
}
const std::vector<Token> &result() {
if (!tokenVector.empty())
return tokenVector;
long long currentPos = 0;
unsigned int lineNumber = 0;
for (const auto &str : inputStrings) {
++lineNumber;
std::string data;
std::stringstream sstream(str);
while (sstream >> data) {
if (tokenMap.count(data) > 0) { // Processing the keywords
Token token(currentPos, data);
tokenVector.push_back(token);
tokenToLine.push_back(lineNumber);
currentPos = sstream.tellg();
continue;
}
auto dataVector = splitData(data);
for (auto &data_ : dataVector) {
if (tokenMap.count(data_) > 0) {
Token token(currentPos, data_);
tokenVector.push_back(token);
tokenToLine.push_back(lineNumber);
currentPos = sstream.tellg();
} else { // The token is an indentifier
if (identifierMap.count(data_) > 0) { // Was found previously
Token token(currentPos, identifierMap[data_]);
tokenVector.push_back(token);
tokenToLine.push_back(lineNumber);
} else {
Token token(currentPos, freeTokenId);
identifierMap[data_] = freeTokenId++;
tokenVector.push_back(token);
tokenToLine.push_back(lineNumber);
}
currentPos = sstream.tellg();
}
}
currentPos = sstream.tellg();
}
}
return tokenVector;
}
typedef std::map<std::string, int> tMap;
typedef std::map<int, std::string> rtMap;
static tMap identifierMap;
static tMap tokenMap;
static rtMap reverseTokenMap;
static rtMap initReverseTokenMap() {
rtMap map;
for (auto &it : tokenMap)
map[it.second] = it.first;
return map;
}
const std::vector<unsigned int> &getTokenToLine() const {
return tokenToLine;
}