-2

I'm trying to implement this transition function algorithm in ruby.

Here is the algorithm:

Compute-Transition-Function(P, Σ);
  m := |P|
  for q=0 to m
    for each a∈Σ
      k := min(m + 1, q + 2)
      repeat
        k=k−1
      until (Pk ⊐ Pqa)
      δ(q, a) := k
return δ

And here is what I've done so far in ruby:

def compute_transition_function(pattern, alphabet)
  m = pattern.length
  transition = Array.new()

  m.times do |q|
    alphabet.each do |c|
      k = [m+1, q+2].min
      while pattern[q+c][-k] != pattern[k]
        k -= 1
      end
      transition[q][c] = k
    end
  end

  return transition
end

This is what I get when I compiled.

finiteautomatamatcher.rb:54:in `+': String can't be coerced into Fixnum (TypeError)
from project.rb:54:in `block (2 levels) in compute_transition_function'
from project.rb:52:in `each'
from project.rb:52:in `block in compute_transition_function'
from project.rb:51:in `times'
from project.rb:51:in `compute_transition_function'
from project.rb:82:in `<main>'
sawa
  • 165,429
  • 45
  • 277
  • 381
kuat
  • 1
  • 2

2 Answers2

0

the problem is with c I suppose. Alphabet suggests mi it is an array of string, am I correct? If so, you will always get error as String does not implement + method. Probably you should convert (ASCII number?) those strings into numbers.

djaszczurowski
  • 4,385
  • 1
  • 18
  • 28
0

Without getting into the details of the function, to fix this error:

`+': String can't be coerced into Fixnum (TypeError)

You need to convert your Strings into Fixnums using to_i before attempting addition (+). Since there isn't enough code to know what datatypes are in use, a possible code change may be (assuming that c is a string):

while pattern[q+c.to_i][-k] != pattern[k]
  k -= 1
end