Class: Urm::Machine

Inherits:
Object
  • Object
show all
Defined in:
lib/urm/machine.rb

Overview

The Machine class represents an Unlimited Register Machine (URM) capable of executing a series of instructions on a set of registers. Machine is initialized with a specified number of input parameters.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_size) ⇒ Machine

Initializes a new URM machine with n input parameters

Parameters:

  • input_size (Integer)

    The number of input parameters



16
17
18
19
# File 'lib/urm/machine.rb', line 16

def initialize(input_size)
  @registers = Array.new(input_size + 1, 0)
  @instructions = []
end

Instance Attribute Details

#instructionsObject (readonly)

Returns the value of attribute instructions.



11
12
13
# File 'lib/urm/machine.rb', line 11

def instructions
  @instructions
end

#registersObject (readonly)

Returns the value of attribute registers.



11
12
13
# File 'lib/urm/machine.rb', line 11

def registers
  @registers
end

Instance Method Details

#add(instruction) ⇒ Object

Adds an instruction to the machine

Parameters:



24
25
26
27
28
29
30
31
32
33
# File 'lib/urm/machine.rb', line 24

def add(instruction)
  instruction =
    case instruction
    when String
      Urm::Instruction.parse(instruction)
    else
      instruction
    end
  @instructions[instruction.label - 1] = instruction
end

#add_all(instructions) ⇒ Object

Adds an array of instructions to the machine

Parameters:

  • instructions (Array<Urm::Instruction, String>)

    The array of instructions to add



38
39
40
41
42
# File 'lib/urm/machine.rb', line 38

def add_all(instructions)
  instructions.each do |instruction|
    add(instruction)
  end
end

#run(*inputs) ⇒ Integer

Runs the machine with the given input values and returns the value of x1

Parameters:

  • inputs (Array<Integer>)

    The input values

Returns:

  • (Integer)

    The value of x1 after execution



48
49
50
51
52
# File 'lib/urm/machine.rb', line 48

def run(*inputs)
  validate_instructions
  initialize_registers(inputs)
  execute_instructions
end

#run_and_print(*inputs) ⇒ Object

Runs the machine with the given input values and prints the value of x1

Parameters:

  • inputs (Array<Integer>)

    The input values



57
58
59
60
# File 'lib/urm/machine.rb', line 57

def run_and_print(*inputs)
  result = run(*inputs)
  puts result
end

#validate_instructionsObject

Validates the instructions to ensure there are no references to non-existent labels and there is exactly one stop instruction.



64
65
66
67
68
# File 'lib/urm/machine.rb', line 64

def validate_instructions
  labels = collect_labels
  validate_labels(labels)
  validate_stop_instructions
end