-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMarkovChain.java
More file actions
67 lines (56 loc) · 1.46 KB
/
MarkovChain.java
File metadata and controls
67 lines (56 loc) · 1.46 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
package DesignExcercise;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class MarkovChain {
Map<String, Map<String, Integer>> markov;
Map<String, Integer> wordCount;
public MarkovChain() {
super();
markov = new HashMap<String, Map<String, Integer>>();
wordCount = new HashMap<String, Integer>();
}
void add(String w1, String w2) {
if (!wordCount.containsKey(w1)) {
wordCount.put(w1, 0);
}
wordCount.put(w1, wordCount.get(w1) + 1);
if (w2 != null) {
if (!markov.containsKey(w1)) {
markov.put(w1, new HashMap<String, Integer>());
}
if (!markov.get(w1).containsKey(w2)) {
markov.get(w1).put(w2, 0);
}
markov.get(w1).put(w2, markov.get(w1).get(w2) + 1);
}
}
String getNextWord(String word) {
Random r = new Random();
double t = r.nextDouble();
for (String w2 : markov.get(word).keySet()) {
int count = markov.get(word).get(w2);
double prob = count / (double) wordCount.get(word);
if (prob > t) {
return w2;
}
t -= prob;
}
return null;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] wordList = {"a", "b", "a", "c", "a", "d", "a", "d"};
MarkovChain mc = new MarkovChain();
for (int i = 0; i < wordList.length - 1; ++i) {
mc.add(wordList[i], wordList[i + 1]);
}
mc.add(wordList[wordList.length - 1], null);
for (int i = 0; i < 10; ++i) {
System.out.print(mc.getNextWord("d"));
}
}
}