Class: RandomData::MarkovGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/random_data/markov.rb

Instance Method Summary collapse

Constructor Details

#initialize(memory = 1) ⇒ MarkovGenerator

Returns a new instance of MarkovGenerator.



7
8
9
10
11
# File 'lib/random_data/markov.rb', line 7

def initialize(memory = 1)
  @memory_size = memory
  @table = Hash.new {|h,k| h[k] = {}}
  @state = []
end

Instance Method Details

#generate(n = 1, clear_state = false) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/random_data/markov.rb', line 34

def generate(n=1, clear_state=false)
  @state = [] if clear_state
  results = []
  n.times do
    retry_count = 0
    begin
      result_hash = @table[Marshal.dump(@state)]
      the_keys,the_vals = [],[]
      result_hash.each_pair do |k,v|
        the_keys << k
        the_vals << v
      end
      # get the weighted random value, by index.
      i = the_vals.roulette
    rescue
      # puts "results:#{result_hash.inspect}";
      # puts "keys:#{the_keys.inspect}";
      # puts "vals:#{the_vals.inspect}";
      # puts "state:#{@state.inspect}";
      @state = []
      retry_count += 1
      if retry_count < 5
        retry 
      else
        # puts
        # puts "table:#{@table.inspect}";
        raise
      end
    end
    result = the_keys[i]
    # puts "index:#{i.inspect}";

    next_state(result)
    if block_given?
      yield result
    end
    results << result
  end
  return results
end

#insert(result) ⇒ Object

given the next token of input add it to the table



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/random_data/markov.rb', line 16

def insert(result)
  # puts "insert called with #{result}"
  tabindex = Marshal.dump(@state)
  if @table[tabindex].has_key?(result)
    @table[tabindex][result] += 1
  else
    @table[tabindex][result] = 1
  end
  # puts "table #{@table.inspect}"
  next_state(result)
end

#next_state(result) ⇒ Object



28
29
30
31
32
# File 'lib/random_data/markov.rb', line 28

def next_state(result)
  @state.shift if @state.size >= @memory_size
  @state.push(result)
  # puts "@state is #{@state.inspect}"
end