aboutsummaryrefslogtreecommitdiff
path: root/markov-generate.rb
blob: 4213a589cba6a2d68a2b3f451ad7eb0e1ee4e4b1 (plain)
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
module Markov
	class Generator
		def initialize(input, type=:var)
			@prng = Random.new(Time.now.to_i)
			if type == :var then
				@stats = input
			elsif type == :file then
				@stats = Marshal::load(File.open(input).read)
			end
			@chunklength = @stats["__SETTINGS__"]["__CHUNKLENGTH__"]
		end

		def cfd(hash)
			tot = 0
			hash.each_pair {|k, v|
				hash[k] = tot += v
			}
		end

		def sel(hash)
			max = hash.values.max
			r = @prng.rand(max*100000) % max
			hash.each_pair {|k, v|
				return k if r < v
			}
		end

		def aword(chunk, hash)
			sel(cfd(hash[chunk]))
		end

		def generate(length)
			current = @stats.keys.select{|k| k != "__SETTINGS__" }.sample

			(length - @chunklength).times do
				current << aword(current[-@chunklength..-1], @stats)
			end

			puts current.join(" ")
		end
	end
end