aboutsummaryrefslogtreecommitdiff
path: root/markov-generate.rb
diff options
context:
space:
mode:
Diffstat (limited to 'markov-generate.rb')
-rwxr-xr-xmarkov-generate.rb38
1 files changed, 38 insertions, 0 deletions
diff --git a/markov-generate.rb b/markov-generate.rb
new file mode 100755
index 0000000..36d80a1
--- /dev/null
+++ b/markov-generate.rb
@@ -0,0 +1,38 @@
+module Markov
+ class Generator
+ def initialize(inputfile)
+ @prng = Random.new(Time.now.to_i)
+ @stats = Marshal::load(File.open(inputfile).read)
+ @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