-
Notifications
You must be signed in to change notification settings - Fork 0
/
Markov.rb
39 lines (35 loc) · 981 Bytes
/
Markov.rb
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
class MarkovChain
def initialize(text)
@words = Hash.new
wordlist = text.split
wordlist.each_with_index do |word, index|
add(word, wordlist[index + 1]) if index <= wordlist.size - 2
end
end
def add(word, next_word)
@words[word] = Hash.new(0) if !@words[word]
@words[word][next_word] += 1
end
def get(word)
return "" if !@words[word]
followers = @words[word]
sum = followers.inject(0) {|sum,kv| sum += kv[1]}
random = rand(sum)+1
partial_sum = 0
next_word = followers.find do |word, count|
partial_sum += count
partial_sum >= random
end.first
next_word
end
end
mc = MarkovChain.new(
File.read("DorianGray.txt")
)
sentence = ""
word = "Fishpingle"
until sentence.count(".") == 10
sentence << word << " "
word = mc.get(word)
end
puts sentence << "\n\n"