import java.util.*; /** * Deterministic finite automata example * * Specify states as an array of their names, with ",S" (start) after one of them and ",E" (end) after at least one of them * Specify transitions as an array of "from,to,label" for a unique label or "from,to,label1,label2,..." for more * * Then try matching a string * * @author Chris Bailey-Kellogg, Dartmouth CS 10, Winter 2014 * @author inspired by a CS 8 problem set by Scot Drysdale (more beautiful in Haskell, of course) * @author CBK, small revisions, Spring 2016 * */ public class DFA { String start; Set ends; Map> transitions; // state -> (character -> next state) /** * Constructs the DFA from the arrays, as specified in the overall header */ DFA(String[] ss, String[] ts) { ends = new TreeSet(); transitions = new TreeMap>(); // States for (String v : ss) { String[] pieces = v.split(","); if (pieces.length>1) { if (pieces[1].equals("S")) start = pieces[0]; else if (pieces[1].equals("E")) ends.add(pieces[0]); } } // Transitions for (String e : ts) { String[] pieces = e.split(","); String from = pieces[0], to = pieces[1]; if (!transitions.containsKey(from)) transitions.put(from, new TreeMap()); for (int i=2; i