Sha256: fe5da2ea70620c3cceaed63c4fbc7c14a39f8b54dbcd82c1cd3769b8fdb17b91

Contents?: true

Size: 1.01 KB

Versions: 8

Compression:

Stored size: 1.01 KB

Contents

module Markov
  class TransitionMatrix
    attr_reader :depth, :transitions

    def initialize(transitions={}, depth:)
      @depth = depth
      @transitions = transitions
    end

    def add_transition(states)
      # p [ :add_transition, states: states, depth: depth ]
      if states.is_a?(Array) && states.count > @depth
        states = states[-(@depth)..-1]
      end

      unless states.count == depth
        raise "This transition matrix is depth #@depth, not #{states.count}!"
      end

      *key, last = states
      key.inject(@transitions) { |h,k| h[k] ||= {}; h[k] }
      key.inject(@transitions, :fetch)[last] ||= 0
      key.inject(@transitions, :fetch)[last] += 1
    end

    def transitions_from(states)
      states = [states] unless states.is_a?(Array)

      if states.count >= @depth
        states = states[-(@depth-1)..-1]
      end

      if @depth == 1
        states = []
      end

      if states.count > 0
        @transitions.dig(*states)
      else
        @transitions
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
markov-rb-0.1.9 lib/markov/transition_matrix.rb
markov-rb-0.1.8 lib/markov/transition_matrix.rb
markov-rb-0.1.7 lib/markov/transition_matrix.rb
markov-rb-0.1.6 lib/markov/transition_matrix.rb
markov-rb-0.1.5 lib/markov/transition_matrix.rb
markov-rb-0.1.4 lib/markov/transition_matrix.rb
markov-rb-0.1.3 lib/markov/transition_matrix.rb
markov-rb-0.1.2 lib/markov/transition_matrix.rb