Class: Automata::Tape

Inherits:
Object
  • Object
show all
Defined in:
lib/automata/turing.rb

Overview

Turing Machine tape

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string = nil) ⇒ Tape

Creates a new tape.

Parameters:

  • string (String) (defaults to: nil)

    the input string



113
114
115
116
117
118
119
120
121
# File 'lib/automata/turing.rb', line 113

def initialize(string=nil)
  if string
    @memory = []
    @memory << '@' unless string[0] == '@'
    @memory += string.split('')
    @memory << '@' unless string[-1] == '@'
    @head = 1
  end
end

Instance Attribute Details

#memoryObject

Returns the value of attribute memory.



108
109
110
# File 'lib/automata/turing.rb', line 108

def memory
  @memory
end

Instance Method Details

#outputString

Trims the memory empty cells and outputs the tape string.

Returns:

  • (String)

    the tape memory string



152
153
154
# File 'lib/automata/turing.rb', line 152

def output
  @memory.join.sub(/^@*/, '').sub(/@*$/, '')
end

#transition(read, write, move) ⇒ Boolean

Transitions the tape.

Parameters:

  • read (String)

    the input symbol read

  • write (String)

    the symbol to write

  • move (String)

    Either ‘L’, ‘R’, or ‘S’ (default) to move left, right, or stay, respectively.

Returns:

  • (Boolean)

    whether the transition succeeded



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/automata/turing.rb', line 130

def transition(read, write, move)
  if read == @memory[@head]
    @memory[@head] = write
    case move
    when 'R'
      # Move right
      @memory << '@' if @memory[@head + 1]
      @head += 1
    when 'L'
      # Move left
      @memory.unshift('@') if @head == 0
      @head -= 1
    end
    return true
  else
    return false
  end
end