Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. [code]
  2. class DFA < Struct.new(:current_state, :accept_states, :rulebook)
  3. def accepting?
  4. puts accept_states.include?(current_state)
  5. end
  6. def read_character(character)
  7. self.current_state = rulebook.next_state(current_state, character)
  8. end
  9. def read_string(string)
  10. string.chars.each do |character|
  11. read_character(character)
  12. end
  13. end
  14. end
  15. class DFADesign < Struct.new(:start_state, :accept_states, :rulebook)
  16. def to_dfa
  17. DFA.new(start_state, accept_states, rulebook)
  18. end
  19. def accepts?(string)
  20. to_dfa.tap{ |dfa| dfa.read_string(string) }.accepting?
  21. end
  22. end
  23.  
  24.  
  25. class FARule < Struct.new(:state, :character, :next_state)
  26. def applies_to?(state, character)
  27. self.state == state && self.character == character
  28. end
  29.  
  30. def follow
  31. next_state
  32. end
  33.  
  34. def inspect
  35. "#<FARule #{state.inspect } -- #{character} --> #{next_state.inspect}>"
  36. end
  37.  
  38. end
  39.  
  40.  
  41. class DFARulebook < Struct.new(:rules)
  42. def next_state(state, character)
  43. rule_for(state, character).follow
  44. end
  45.  
  46. def rule_for(state, character)
  47. rules.detect{ |rule| rule.applies_to?(state, character) }
  48. end
  49.  
  50. end
  51.  
  52. badRules = (32..128).reject{|v| v=="a".ord or v=="b".ord}.each do |i|
  53. FARule.new(1,i.chr,1)
  54. FARule.new(2,i.chr,2)
  55. FARule.new(3,i.chr,3)
  56. end
  57. rulebook = DFARulebook.new([
  58. FARule.new(1,"a",2), FARule.new(1,"b",1), FARule.new(2,"a", 2),
  59. FARule.new(2,"b",3), FARule.new(3,"a",3), FARule.new(3,"b", 3),
  60. badRules.each
  61. ])
  62. rulebook.next_state(1,"a")
  63. rulebook.next_state(1,"b")
  64. puts "Looking for accepting state"
  65. dfa = DFA.new(1,[3],rulebook)
  66. dfa.accepting?
  67. dfa_design = DFADesign.new(1,[3],rulebook)
  68. dfa_design.accepts?('aaaaffaaa')
  69.  
  70. puts "Testing making new automata object"
  71. DFA.new(2,[1,3],rulebook).accepting?
  72. DFA.new(3,[1,3],rulebook).accepting?
  73. [/code]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement