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 * @author Tim Pierson, Winter 2017 - small factoring and added some additional comments * @author Tim Pierson, Dartmouth CS 10, provided for Winter 2025 */ public class DFA { String start; //assume only one starting position Set ends; //possibly multiple end states, hence the set instead of a single string Map> transitions; // state -> (character -> next state) ex. "A,B,0" means from A go to B if given a 0 /** * Constructs the DFA from the arrays, as specified in the overall header */ DFA(String[] ss, String[] ts) { ends = new TreeSet(); transitions = new TreeMap>(); // Parse states for (String v : ss) { String[] pieces = v.split(","); //pieces[0] = state name, {pieces[1] = start | end} //look for start and end markers if (pieces.length>1) { if (pieces[1].equals("S")) { start = pieces[0]; } else if (pieces[1].equals("E")) { ends.add(pieces[0]); } } } // Parse transitions for (String e : ts) { String[] pieces = e.split(","); //pieces[0] = starting from this node, pieces[1] = move to this node, pieces[2] = if given this input (e.g., "A,B,0" = from A move to B if given 0) String from = pieces[0]; String to = pieces[1]; if (!transitions.containsKey(from)) { transitions.put(from, new TreeMap()); } for (int i=2; i