aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorNathan Lasseter <nathan@4574.co.uk>2014-01-19 12:47:38 +0000
committerNathan Lasseter <nathan@4574.co.uk>2014-01-19 12:47:38 +0000
commit214e8900240e2f98fba5b1553ed792ad8ff6f56f (patch)
treef16b381a4cad2c8da3ad1ca0eb5fce52e0d826de
parent6dd179efd69946dc8c68dc1875db2eb945c5c6dd (diff)
Renames and refactored run
-rwxr-xr-xmarkov-generate.rb38
-rwxr-xr-xmarkov-run.rb39
2 files changed, 38 insertions, 39 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
diff --git a/markov-run.rb b/markov-run.rb
deleted file mode 100755
index 991c5e7..0000000
--- a/markov-run.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-#!/usr/bin/env ruby
-
-PRNG = Random.new(Time.now.to_i)
-
-STATS = Marshal::load(File.open(ARGV[0]).read)
-
-CHUNK = STATS["__SETTINGS__"]["__CHUNK__"]
-
-NUM = (ARGV[2] or "1").to_i
-
-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
-
-NUM.times do
- current = STATS.keys.select{|k| k != "__SETTINGS__" }.sample
-
- (ARGV[1].to_i - CHUNK).times do
- current << aword(current[-CHUNK..-1], STATS)
- end
-
- puts current.join(" ")
- puts
-end