From: Alpha Chen Date: 2008-05-13T09:00:10+09:00 Subject: Re: [QUIZ] The Turing Machine (#162) A pretty simplistic solution: #!/usr/bin/env ruby class Turing def initialize(file, tape=nil) @tape = Hash.new('_') @head = 0 # initialize tape tape.split(//).each_with_index {|c,i| @tape[i] = c } if tape # read program instructions @program = Hash.new File.open(file).each_line do |line| line.gsub!(/#.*/, '') # remove comments next if line =~ /^\s*$/ # skip blank lines line = line.split(/\s+/) @state = line[0] if @state.nil? @program[line[0..1]] = line[2..4] end end def run while next_state = @program[[@state, @tape[@head]]] @state, @tape[@head], dir = next_state @head += (dir == 'R') ? 1 : -1 end puts @tape.sort.map {|_,v| v}.join.gsub(/^_*|_.*$/, '') end end Turing.new(ARGV.shift, ARGV.shift).run if __FILE__ == $0