Guest User

Untitled

a guest
Feb 21st, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. module Turing
  2. class Machine
  3. attr_accessor :rules, :pos, :state
  4. def initialize
  5. @rules = {}
  6. @pos, @state = 0, 0
  7. @tape = []
  8. end
  9. def tape
  10. @tape.join
  11. end
  12. def tape=( str )
  13. @tape.clear
  14. @tape.push *str.split('').map { |x| x.to_i }
  15. end
  16. def run
  17. before = tape
  18. puts " pos state chr mv"
  19. loop do
  20. chr = @tape[@pos] || 0
  21. newstate, newchr, mv = @rules[@state][chr]
  22. puts " #{@pos.to_s.rjust(4)} #{@state}->#{newstate} #{chr}->#{newchr} #{mv}"
  23. # update this position on tape
  24. @tape[@pos] = newchr
  25. # update state
  26. @state = newstate
  27. # move read head
  28. case mv
  29. when :r
  30. @pos += 1
  31. when :l
  32. @pos -= 1
  33. when :x
  34. @pos += 1
  35. break
  36. end
  37. end
  38. [ before, tape ]
  39. end
  40. end
  41. end
  42.  
  43. UNARY_INC = [
  44. [
  45. [0, 0, :r],
  46. [1, 1, :r],
  47. ],
  48. [
  49. [0, 1, :x],
  50. [1, 1, :r],
  51. ]
  52. ]
  53.  
  54.  
  55. UNARY_DBL = [
  56. [
  57. [0, 0, :r],
  58. [1, 0, :r]
  59. ],
  60. [
  61. [2, 1, :l],
  62. [1, 1, :r]
  63. ],
  64. [
  65. [3, 0, :r],
  66. [4, 0, :r]
  67. ],
  68. [
  69. [0, 1, :x],
  70. [3, 1, :r]
  71. ],
  72. [
  73. [5, 1, :l],
  74. [4, 1, :r]
  75. ],
  76. [
  77. [2, 1, :l],
  78. [5, 1, :l]
  79. ]
  80. ]
  81.  
  82. if $0 == __FILE__
  83. t = Turing::Machine.new
  84. if ARGV.length == 2
  85. t.rules = Object.const_get(ARGV.shift)
  86. t.tape = ARGV.shift
  87. else
  88. t.rules = UNARY_INC
  89. t.tape = "00000111"
  90. end
  91. o = t.run
  92. puts " in: #{o.first}"
  93. puts "out: #{o.last}"
  94. end
Add Comment
Please, Sign In to add comment