Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [code]
- class DFA < Struct.new(:current_state, :accept_states, :rulebook)
- def accepting?
- puts accept_states.include?(current_state)
- end
- def read_character(character)
- self.current_state = rulebook.next_state(current_state, character)
- end
- def read_string(string)
- string.chars.each do |character|
- read_character(character)
- end
- end
- end
- class DFADesign < Struct.new(:start_state, :accept_states, :rulebook)
- def to_dfa
- DFA.new(start_state, accept_states, rulebook)
- end
- def accepts?(string)
- to_dfa.tap{ |dfa| dfa.read_string(string) }.accepting?
- end
- end
- class FARule < Struct.new(:state, :character, :next_state)
- def applies_to?(state, character)
- self.state == state && self.character == character
- end
- def follow
- next_state
- end
- def inspect
- "#<FARule #{state.inspect } -- #{character} --> #{next_state.inspect}>"
- end
- end
- class DFARulebook < Struct.new(:rules)
- def next_state(state, character)
- rule_for(state, character).follow
- end
- def rule_for(state, character)
- rules.detect{ |rule| rule.applies_to?(state, character) }
- end
- end
- badRules = (32..128).reject{|v| v=="a".ord or v=="b".ord}.each do |i|
- FARule.new(1,i.chr,1)
- FARule.new(2,i.chr,2)
- FARule.new(3,i.chr,3)
- end
- rulebook = DFARulebook.new([
- FARule.new(1,"a",2), FARule.new(1,"b",1), FARule.new(2,"a", 2),
- FARule.new(2,"b",3), FARule.new(3,"a",3), FARule.new(3,"b", 3),
- badRules.each
- ])
- rulebook.next_state(1,"a")
- rulebook.next_state(1,"b")
- puts "Looking for accepting state"
- dfa = DFA.new(1,[3],rulebook)
- dfa.accepting?
- dfa_design = DFADesign.new(1,[3],rulebook)
- dfa_design.accepts?('aaaaffaaa')
- puts "Testing making new automata object"
- DFA.new(2,[1,3],rulebook).accepting?
- DFA.new(3,[1,3],rulebook).accepting?
- [/code]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement