forked from indy256/codelibrary
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathZFunctionTest.java
More file actions
34 lines (30 loc) · 1.04 KB
/
ZFunctionTest.java
File metadata and controls
34 lines (30 loc) · 1.04 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
package test.strings;
import java.util.Random;
import strings.ZFunction;
public class ZFunctionTest {
// random tests
public static void main(String[] args) {
Random rnd = new Random(1);
for (int step = 0; step < 10_000; step++) {
String s = getRandomString(rnd, 100);
String pattern = getRandomString(rnd, 5);
int pos1 = find(s, pattern);
int pos2 = s.indexOf(pattern);
if (pos1 != pos2)
throw new RuntimeException();
}
}
static int find(String s, String pattern) {
int[] z = ZFunction.zFunction(pattern + "\0" + s);
for (int i = pattern.length() + 1; i < z.length; i++)
if (z[i] == pattern.length())
return i - pattern.length() - 1;
return -1;
}
static String getRandomString(Random rnd, int maxlen) {
int n = rnd.nextInt(maxlen) + 1;
char[] s = new char[n];
for (int i = 0; i < n; i++) s[i] = (char) ('a' + rnd.nextInt(3));
return new String(s);
}
}