-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.rb
50 lines (40 loc) · 1.17 KB
/
chain.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
40
41
42
43
44
45
46
47
48
class TransitionMatrix
def initialize
@matrix = Hash.new
@probabilistic_matrix = Hash.new
end
def add(from_first, from_second, to)
from = from_first + ' ' + from_second
@matrix[from] = Hash.new(0) unless @matrix.has_key? from
@matrix[from][to] += 1
@probabilistic_matrix[from] = nil
end
def count
@matrix.inject(0) do |total, (from, to)|
total + count_of_row(from)
end
end
def count_of_row(word)
@matrix[word].values.inject(:+)
end
def transitions(word)
@probabilistic_matrix[word] ||= @matrix[word].inject({}) do |matrix, (to_word, to_count)|
matrix[to_word] = to_count.to_f / count_of_row(word).to_f
matrix
end
end
def cumulative_transitions(word)
transitions(word).inject({:matrix => {}, :total => 0.0}) do |prob_set, (to_word, to_prob)|
prob_set[:matrix][to_word] = Range.new(prob_set[:total], prob_set[:total] + to_prob, true)
prob_set[:total] += to_prob
prob_set
end.fetch(:matrix)
end
def keys
@matrix.keys
end
def get_next(word)
rand = Random.rand
cumulative_transitions(word).select {|to_word, to_prob| to_prob.cover? rand }.keys.first
end
end