Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'set'
- class NFA
- attr_reader :alphabet
- @transitions = Hash.new
- def initialize(file)
- @filename = file
- File.open(file).each_with_index do |line, number|
- parse(line, number)
- end
- end
- def transition_function(state, symbol)
- @transitions[[state, symbol]]
- end
- private
- def parse(line, number)
- temp_array = line.strip.split(', ').map{|e| e.to_sym}
- tokens = Set.new
- if (temp_array.uniq == temp_array)
- tokens = Set.new temp_array
- else
- parse_error("Does not form a set", number) unless temp_array.uniq == tokens
- end
- #This method parses lines differently based on where they are in the file, as per the format
- #specificed in the assignment. Keep in mind thatthat "number" starts at 0.
- #
- # 0. alphabet, or input symbols
- # 1. NFA states
- # 2. starting states - which of course should be a singleton
- # 3. the set of all final or accepting states
- #
- # All sequent lines represent transition functions
- case number
- when 0
- @alphabet = tokens
- when 1
- @states = tokens
- when 2
- if (tokens.length != 1) then
- parse_error "More than one start state in input file.", line
- elsif (not tokens.proper_subset? @states)
- parse_error "The start state is not a state of the DFA", line
- else
- @start_state = tokens
- end
- when 3
- if(not tokens.proper_subset? @states) then
- parse error "Final states are not a subset of the accepting states", line
- else
- @accepting_states = tokens
- end
- else
- @transitions[temp_array[0, 1]] = temp_array[2]
- end
- end
- def parse_error(msg, number)
- raise "line #{number}, #{@filename}\n #{msg}"
- end
- end
Add Comment
Please, Sign In to add comment