Skip to content

Instantly share code, notes, and snippets.

@kejadlen
Last active April 22, 2017 16:04
Show Gist options
  • Save kejadlen/99f7a847d963399008bf74b083e16aba to your computer and use it in GitHub Desktop.
Save kejadlen/99f7a847d963399008bf74b083e16aba to your computer and use it in GitHub Desktop.
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[
File.readlines(file)
.map {|line| line.gsub(/#.*$/, '') } # remove comments
.map(&:strip).reject(&:empty?) # skip blank lines
.map {|line| line.split(/\s+/) }
.map {|line| [line[0..1], line[2..4]] }
]
# set the initial state
@state = @program.first[0][0]
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment