Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Turing
- class Machine
- attr_accessor :rules, :pos, :state
- def initialize
- @rules = {}
- @pos, @state = 0, 0
- @tape = []
- end
- def tape
- @tape.join
- end
- def tape=( str )
- @tape.clear
- @tape.push *str.split('').map { |x| x.to_i }
- end
- def run
- before = tape
- puts " pos state chr mv"
- loop do
- chr = @tape[@pos] || 0
- newstate, newchr, mv = @rules[@state][chr]
- puts " #{@pos.to_s.rjust(4)} #{@state}->#{newstate} #{chr}->#{newchr} #{mv}"
- # update this position on tape
- @tape[@pos] = newchr
- # update state
- @state = newstate
- # move read head
- case mv
- when :r
- @pos += 1
- when :l
- @pos -= 1
- when :x
- @pos += 1
- break
- end
- end
- [ before, tape ]
- end
- end
- end
- UNARY_INC = [
- [
- [0, 0, :r],
- [1, 1, :r],
- ],
- [
- [0, 1, :x],
- [1, 1, :r],
- ]
- ]
- UNARY_DBL = [
- [
- [0, 0, :r],
- [1, 0, :r]
- ],
- [
- [2, 1, :l],
- [1, 1, :r]
- ],
- [
- [3, 0, :r],
- [4, 0, :r]
- ],
- [
- [0, 1, :x],
- [3, 1, :r]
- ],
- [
- [5, 1, :l],
- [4, 1, :r]
- ],
- [
- [2, 1, :l],
- [5, 1, :l]
- ]
- ]
- if $0 == __FILE__
- t = Turing::Machine.new
- if ARGV.length == 2
- t.rules = Object.const_get(ARGV.shift)
- t.tape = ARGV.shift
- else
- t.rules = UNARY_INC
- t.tape = "00000111"
- end
- o = t.run
- puts " in: #{o.first}"
- puts "out: #{o.last}"
- end
Add Comment
Please, Sign In to add comment