summaryrefslogtreecommitdiff
path: root/test/string/rollingHash.cpp
blob: d19a1530285fe2015b40ffa1dc266192038c2be5 (plain)
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 "../util.h"
#include <string/rollingHash.cpp>

string thueMorse(ll n) {
	string res = "a";
	while (ssize(res) < n) {
		string tmp = res;
		for (char& c : tmp) c ^= 1;
		res += tmp;
	}
	return res;
}

auto getHash(const string& s) {
	return Hash(s)(0, ssize(s));
}

void testThueMorse() {
	set<decltype(getHash(""))> got;
	set<string> expected;
	string s = thueMorse(1000);
	Hash h(s);
	for (int l = 0; l < ssize(s); l++) {
		for (int r = l + 1; r <= ssize(s); r++) {
			got.insert(h(l, r));
			expected.insert(s.substr(l, r - l));
		}
	}
	if (ssize(got) != ssize(expected)) cerr << "error: thueMorse" << FAIL;
	cerr << "thueMorse: ok" << endl;
}

void testTiny() {
	if (getHash("aa") == getHash("a")) cerr << "error: tiny" << FAIL;
	if (getHash("00") == getHash("0")) cerr << "error: tiny" << FAIL;
	if (getHash("AA") == getHash("A")) cerr << "error: tiny" << FAIL;
	cerr << "tiny: ok" << endl;
}

void testSmall(int depth) {
	set<decltype(getHash(""))> got;
	ll expected = 0;
	auto dfs = [&](auto&& self, string pref)->void {
		expected++;
		got.insert(getHash(pref));
		if(ssize(pref) >= depth) return;
		for (char c = 'a'; c <= 'z'; c++) {
			self(self, pref + c);
		}
	};
	dfs(dfs, "");
	if (ssize(got) != expected) cerr << "error: small" << FAIL;
	cerr << "small: ok" << endl;
}

void stress_test() {
	set<decltype(getHash(""))> got;
	set<string> expected;
	string s = Random::string(1000, "abc");
	Hash h(s);
	for (int l = 0; l < ssize(s); l++) {
		for (int r = l + 1; r <= ssize(s); r++) {
			got.insert(h(l, r));
			expected.insert(s.substr(l, r - l));
		}
	}
	if (ssize(got) != ssize(expected)) cerr << "error: stress test" << FAIL;
	cerr << "stress test: ok" << endl;
}

constexpr int N = 1'000'000;
void performance_test() {
	timer t;
	auto s = Random::string(N, "a") + Random::string(N, "ab") + Random::string(N, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789$#");
	hash_t hash = 0;
	t.start();
	Hash h(s);
	for (ll i = 0; i < N; i++) {
		hash += h(i, i + 2*N);
	}
	t.stop();
	if (t.time > 500) cerr << "too slow: " << t.time << FAIL;
	cerr << "tested performance: " << t.time << "ms (hash: " << hash << ")" << endl;
}

int main() {
	testThueMorse();
	testTiny();
	testSmall(sanitize ? 4 : 5);
	stress_test();
	if (!sanitize) performance_test();
}