-
Notifications
You must be signed in to change notification settings - Fork 2
/
SuffixCounter.java
60 lines (56 loc) · 1.51 KB
/
SuffixCounter.java
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
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Scanner;
/**
* Similar to FrequencyCounter, but also counts the suffixes for each k-length substring in the text.
* @author Daniel Friedman
*
*/
public class SuffixCounter {
public static void main(String[] args) {
String text;
int k = 0;
if (args.length == 1) {
k = Integer.parseInt(args[0]);
}
System.out.print("Enter string: ");
Scanner s = new Scanner(System.in);
text = s.nextLine();
MyHashMap<String, Markov> hash = new MyHashMap<String, Markov>();
int distinct = 0;
for (int i=0; i<=text.length()-k; i++) {
String sub = text.substring(i,i+k);
Character suffix = null;
if (((i+k) <= (text.length()-1)))
suffix = text.charAt(i+k);
if (hash.containsKey(sub)) {
Markov temp = hash.get(sub);
if (!(suffix == null)) {
temp.add(suffix);
hash.put(sub, temp);
}
}
else {
Markov m;
if (!(suffix == null)) {
m = new Markov(sub, suffix);
hash.put(sub, m);
distinct++;
}
}
}
System.out.println(distinct+" distinct keys");
Iterator<String> keys = hash.keys();
while (keys.hasNext()) {
String hashKey = keys.next();
Markov hashValue = hash.get(hashKey);
System.out.print(hashValue.count()+" "+hashKey+":");
for (Entry<Character, Integer> entry : hashValue.getMap().entrySet()) {
char suffix = entry.getKey();
int frequencyCount = entry.getValue();
System.out.print(" "+frequencyCount+" "+suffix);
}
System.out.println();
}
}
}