-
Notifications
You must be signed in to change notification settings - Fork 42
/
markov.js
49 lines (46 loc) · 1.46 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
40
41
42
43
44
45
46
47
48
49
function compute_ngrams(sentences, order) {
const ngrams = {"": []}
for(let i=0; i<sentences.length; ++i) {
const words = sentences[i].split(/\s+/)
for(let j=0; j<words.length-order; ++j) {
const Gram = words.slice(j, j+order).join(' ')
if(j === 0) ngrams[""].push(Gram)
const gram = Gram.toLowerCase()
const next = words[j+order]
if(ngrams[gram] == null) ngrams[gram] = []
ngrams[gram].push(next)
}
}
return ngrams
}
function generate_sentence(ngrams, rnd) {
const choose = (a) => a[Math.floor(rnd()*a.length)]
let sentence = choose(ngrams['']).split(' ')
const order = sentence.length
while(true) {
const last = sentence.slice(-order).join(' ').toLowerCase()
const following = ngrams[last]
if(following == null) break
sentence.push(choose(following))
}
return sentence
}
function generate_exercise(ngrams, word_count, rnd) {
let words = []
let chars_left = word_count * 5 + 1
while (chars_left > 0) {
const sentence = generate_sentence(ngrams, rnd)
chars_left -= 1 + sentence.join(' ').length
words.splice(words.length, 0, ...sentence)
}
return new TypeJig.Exercise(words, 0, false, 'ordered');
}
let jig
window.addEventListener('load', () => jig = loadExercisePage(args => {
const ngrams = compute_ngrams(sentences, 3)
const nwords = args.word_count==null ? 100 : parseInt(args.word_count)
return {
generate: (rnd, options) => generate_exercise(ngrams, nwords, rnd),
options: { name: "Markov-chain generated sentences" }
}
}))