-
Notifications
You must be signed in to change notification settings - Fork 0
/
markov.js
40 lines (27 loc) · 1.18 KB
/
markov.js
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
var MARKOV_SENTINEL_WORD = "SENTINEL";
function Markov(source) {
words = source.trim().split(/\s+/);
var prefix_tab = {};
var current_prefix = [MARKOV_SENTINEL_WORD, MARKOV_SENTINEL_WORD];
for (var i = 0; i<words.length; i++) {
prefix_tab[current_prefix] = prefix_tab[current_prefix] || [];
prefix_tab[current_prefix].push(words[i]);
current_prefix.shift();
current_prefix.push(words[i]);
}
prefix_tab[current_prefix] = prefix_tab[current_prefix] || [];
prefix_tab[current_prefix].push(MARKOV_SENTINEL_WORD);
this.generate = function(maxwords) {
var generated = "";
var current_prefix = [MARKOV_SENTINEL_WORD, MARKOV_SENTINEL_WORD];
while(maxwords-- > 0) {
var list = prefix_tab[current_prefix];
var nextWord = list[Math.floor(Math.random() * list.length)];
if(nextWord == MARKOV_SENTINEL_WORD) break;
generated += nextWord + " ";
current_prefix.shift();
current_prefix.push(nextWord);
}
return generated;
}
}