Guest User

Untitled

a guest
Jan 23rd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.02 KB | None | 0 0
  1. require 'set'
  2.  
  3. class NFA
  4. attr_reader :alphabet
  5.  
  6. @transitions = Hash.new
  7.  
  8. def initialize(file)
  9. @filename = file
  10.  
  11. File.open(file).each_with_index do |line, number|
  12. parse(line, number)
  13. end
  14. end
  15.  
  16. def transition_function(state, symbol)
  17. @transitions[[state, symbol]]
  18. end
  19.  
  20. private
  21. def parse(line, number)
  22.  
  23. temp_array = line.strip.split(', ').map{|e| e.to_sym}
  24. tokens = Set.new
  25.  
  26. if (temp_array.uniq == temp_array)
  27. tokens = Set.new temp_array
  28. else
  29. parse_error("Does not form a set", number) unless temp_array.uniq == tokens
  30. end
  31.  
  32. #This method parses lines differently based on where they are in the file, as per the format
  33. #specificed in the assignment. Keep in mind thatthat "number" starts at 0.
  34. #
  35. # 0. alphabet, or input symbols
  36. # 1. NFA states
  37. # 2. starting states - which of course should be a singleton
  38. # 3. the set of all final or accepting states
  39. #
  40. # All sequent lines represent transition functions
  41. case number
  42. when 0
  43. @alphabet = tokens
  44. when 1
  45. @states = tokens
  46. when 2
  47. if (tokens.length != 1) then
  48. parse_error "More than one start state in input file.", line
  49. elsif (not tokens.proper_subset? @states)
  50. parse_error "The start state is not a state of the DFA", line
  51. else
  52. @start_state = tokens
  53. end
  54. when 3
  55. if(not tokens.proper_subset? @states) then
  56. parse error "Final states are not a subset of the accepting states", line
  57. else
  58. @accepting_states = tokens
  59. end
  60. else
  61. @transitions[temp_array[0, 1]] = temp_array[2]
  62. end
  63. end
  64.  
  65. def parse_error(msg, number)
  66. raise "line #{number}, #{@filename}\n #{msg}"
  67. end
  68. end
Add Comment
Please, Sign In to add comment