class Instructions
Attributes
initial_state[RW]
Public Class Methods
new(filename)
click to toggle source
# File bin/tm, line 64 def initialize(filename) re = Regexp.compile('\s* (\w+) \s+ (\w) \s+ (\w+) \s+ (\w) \s+ ([RL])', Regexp::EXTENDED) @instructions = Hash.new { |hash, key| hash[key] = Hash.new } File.open(filename) do |file| file.each_line do |line| if data = re.match(line) then st = data[1].to_sym ch = data[2] @instructions[st][ch] = Transition.new(*data[3 .. 5]) if self.initial_state.nil? self.initial_state = st end end end end end
Public Instance Methods
get_transition(state, char)
click to toggle source
# File bin/tm, line 84 def get_transition(state, char) if @instructions.has_key?(state) && @instructions[state].has_key?(char) return @instructions[state][char] else return nil end end
run(tape, state = self.initial_state)
click to toggle source
# File bin/tm, line 92 def run(tape, state = self.initial_state) raise("Invalid tape") unless tape.respond_to?(:left) && tape.respond_to?(:right) && tape.respond_to?(:read) && tape.respond_to?(:write) while t = get_transition(state, tape.read) state = t.apply do |ch, dir| tape.write(ch) case dir when 'L' tape.left when 'R' tape.right else raise "Invalid direction" end puts tape if VERBOSE end end end