private void ReduceStates() { var newState = 'A'; for (int i = 0; i < States.Count; i++) { if (StartState == States[i]) { StartState = newState.ToString(); } if (FinalStates.Contains(States[i])) { FinalStates[FinalStates.IndexOf(States[i])] = newState.ToString(); } foreach (var tr in Transitions) { if (tr.CurrentState == States[i]) { tr.CurrentState = newState.ToString(); } if (tr.NextState == States[i]) { tr.NextState = newState.ToString(); } } States[i] = newState.ToString(); newState++; } }
private void RemoveObjectsInvolvingState(string stateName) { List <Instruction> temp = new List <Instruction>(); // Remove related instructions foreach (Instruction instruction in Instructions) { if (instruction.CurrentState == stateName || instruction.NextState == stateName) { temp.Add(instruction); } } foreach (Instruction instruction in temp) { Instructions.Remove(instruction); } // Remove related final states if (FinalStates.Contains(stateName)) { FinalStates.Remove(stateName); } // Remove related initial state RemoveInitialStateInvolvingState(stateName); }
public bool TestInput(string input) { Log += ConsoleWriter.Info("Trying to parse: " + input) + "\n"; if (InvalidInput(input)) { return(false); } var currentState = StartState; var steps = new StringBuilder(); foreach (var symbol in input.ToCharArray()) { var transitions = TransitionFunctions; var transition = transitions.Find(t => t.InputState == currentState && t.InputSymbol == symbol); if (transition == null) { Log += ConsoleWriter.Failure("No transitions for current state and symbol") + "\n"; Log += ConsoleWriter.Failure(steps.ToString()) + "\n"; return(false); } currentState = transition.OutputState; steps.Append(transition + "\n"); } if (FinalStates.Contains(currentState)) { Log += ConsoleWriter.Success("Accepted the input with steps:\n" + steps) + "\n"; return(true); } Log += ConsoleWriter.Failure("Stopped in state " + currentState + " which is not a final state.") + "\n"; Log += ConsoleWriter.Failure(steps.ToString()) + "\n"; return(false); }
/// <summary> /// Adds a letter to a language, then returns the string /// </summary> /// <param name="remainingLength">The remaining length for the string</param> /// <param name="stringSoFar">The string generated so far.</param> /// <param name="state">The state from which to generate a letter.</param> /// <returns>Either returns a valid string, or an empty string if there is a non valid string.</returns> private string AddLetterToLanguage(int remainingLength, string stringSoFar, T state) { string resultingString = string.Empty; if (remainingLength > 0) { remainingLength = remainingLength - 1; IEnumerable <Transition <T> > validTransitions = Transitions.Where(x => x.FromState.Equals(state)); foreach (Transition <T> transition in validTransitions) { string newString = string.Concat(stringSoFar, transition.Identifier); resultingString = AddLetterToLanguage(remainingLength, newString, transition.ToState); if (string.IsNullOrEmpty(resultingString)) { continue; } else { break; } } } else { resultingString = FinalStates.Contains(state) ? stringSoFar : string.Empty; } return(resultingString); }
/// <summary> /// Recursively checks to see if we can form the string /// </summary> /// <param name="state">the state to check</param> /// <param name="remainingString">the remainder of the string to check</param> /// <returns>A boolean that is true if the string has been fully formed</returns> private bool CheckNextNodeDfa(T state, string stringToVerify) { bool stringIsAccepted = false; if (stringToVerify == string.Empty) //Early escape if we're finished { stringIsAccepted = FinalStates.Contains(state); return(stringIsAccepted); } char currentCharacter = stringToVerify[0]; if (stringToVerify.Count() > 1) { stringToVerify = stringToVerify.Substring(1); } else { stringToVerify = string.Empty; } IEnumerable <Transition <T> > validTransitions = Transitions.Where(x => x.Identifier == currentCharacter && x.FromState.Equals(state)); foreach (Transition <T> transition in validTransitions) { stringIsAccepted = CheckNextNodeDfa(transition.ToState, stringToVerify); if (stringIsAccepted) { break; } } return(stringIsAccepted); }
public bool AddFinalState(string stateName) { if (States.Contains(stateName) && !FinalStates.Contains(stateName)) { FinalStates.Add(stateName); return(true); } return(false); }
public bool RemoveFinalState(string stateName) { if (FinalStates.Contains(stateName)) { FinalStates.Remove(stateName); return(true); } return(false); }
public bool IsWordInLanguage(String input, State startState) { //if we can finish now, finish now if (input.Length == 0) { return(FinalStates.Contains(startState)); } return(GetStatesAccessibleFrom(startState, input).Intersect(FinalStates).Count() > 0); }
public void AddFinalState(ail.net.parser.FsaState xi_state, ail.net.parser.Token xi_token) { ail.net.framework.Assert.NonNullReference(xi_state, "xi_state"); ail.net.framework.Assert.NonNullReference(xi_token, "xi_token"); if (!FinalStates.Contains(xi_state.Id)) { xi_state.Token = xi_token; FinalStates.Add(xi_state.Id, xi_state); } }
public KeyValuePair <bool, int> MaxString(string str, int pos) { KeyValuePair <bool, int> MaxStr = new KeyValuePair <bool, int>(); int m = 0; bool res = false; int curState = TakeNewStartState(str[pos]); if (FinalStates.Contains(curState)) { res = true; } int i = pos; while (i < str.Length) { if (IsStateTransitionSignalsContainsSignal(curState, str[i])) { foreach (var state in States) { if (state.NameOfState == curState) { int newState = 0; foreach (var list in state.StateTransitionSignals) { foreach (var elem in list) { if (elem == str[i]) { curState = state.AvailableStates[newState]; } } newState++; } } } if (FinalStates.Contains(curState)) { m = i - pos + 1; res = true; MaxStr = new KeyValuePair <bool, int>(res, m); } i++; } else { return(MaxStr); } } return(MaxStr); }
/// <summary> /// Recursively checks to see if we can form the string /// </summary> /// <param name="givenTransition">the transition to check</param> /// <param name="remainingString">the remainder of the string to check</param> /// <returns>A boolean that is true if the string has been fully formed</returns> private bool CheckNextNodeNdfa(Transition <T> givenTransition, string stringToVerify) { bool stringIsAccepted = false; if (stringToVerify == string.Empty) //Early escape if we're finished { stringIsAccepted = FinalStates.Contains(givenTransition.ToState); if (stringIsAccepted) { return(stringIsAccepted); } IEnumerable <Transition <T> > possibleTransitionsLeadingToEndState = Transitions.Where(x => x.Identifier == '$' && x.FromState.Equals(givenTransition.ToState)); stringIsAccepted = CheckEmptyTransitions(possibleTransitionsLeadingToEndState); return(stringIsAccepted); } char currentCharacter = stringToVerify[0]; if (stringToVerify.Count() > 1) { stringToVerify = stringToVerify.Substring(1); } else { stringToVerify = string.Empty; } IEnumerable <Transition <T> > validTransitions = Transitions.Where(x => (x.Identifier == currentCharacter || x.Identifier == '$') && x.FromState.Equals(givenTransition.ToState)); foreach (Transition <T> transition in validTransitions) { if (transition.Identifier != '$') { stringIsAccepted = CheckNextNodeNdfa(transition, stringToVerify); } else { stringIsAccepted = CheckNextNodeNdfa(transition, currentCharacter + stringToVerify); } if (stringIsAccepted) { break; } } return(stringIsAccepted); }
/// <summary> /// Checks whether the given string fits within this automata /// </summary> /// <param name="stringToVerify">The string to check.</param> /// <returns>A boolean indicator that is true if the string can be formed by this automata by traversing it's nodes.</returns> private bool IsStringAcceptableNdfa(string stringToVerify) { bool stringIsAccepted = false; //Pak start states + eerste element in char array char charToCheckFor = stringToVerify[0]; HashSet <T> startingStates = StartStates; //Verwijder eerste character if (stringToVerify.Count() > 1) { stringToVerify = stringToVerify.Substring(1); } else { stringToVerify = string.Empty; } //Voor iedere uitgaande transitie check of het kan met het gegeven character foreach (T state in startingStates) { if (stringToVerify == string.Empty) { stringIsAccepted = FinalStates.Contains(state); break; } IEnumerable <Transition <T> > validTransitions = Transitions.Where(x => (x.Identifier == charToCheckFor || x.Identifier == '$') && x.FromState.Equals(state)); foreach (Transition <T> transition in validTransitions) { if (transition.Identifier != '$') { stringIsAccepted = CheckNextNodeNdfa(transition, stringToVerify); } else { stringIsAccepted = CheckNextNodeNdfa(transition, charToCheckFor + stringToVerify); } if (stringIsAccepted) { break; } } } //Als er een terug komt met true, dan bestaat de string return(stringIsAccepted); }
protected bool SubVerifyString(string input, string state) { if (input.Length == 0 && FinalStates.Contains(state)) { return(true); } if (input.Length != 0) { var candidateInstructions = Instructions.Where(i => i.CurrentState == state && i.Input == input[0]); foreach (var instruction in candidateInstructions) { if (SubVerifyString(input.Substring(1, input.Length - 1), instruction.NextState)) { return(true); } } } return(false); }
public bool CheckWord(string word) { var currentState = StartState; for (int i = 0; i < word.Length; i++) { var currentLetter = word[i]; var tr = Transitions.Find(a => a.Symbol == currentLetter && a.CurrentState == currentState); if (tr != null) { currentState = tr.NextState; } else { return(false); } } return(FinalStates.Contains(currentState)); }
/// <summary> /// Recursively loop through the automaton /// </summary> /// <returns>An int that is the total count found while looping</returns> private int CountNextState(int previousCount, T state) { int newCount = previousCount + 1; if (FinalStates.Contains(state)) { return(newCount); } else { IEnumerable <Transition <T> > transitionsForThisState = Transitions.Where(x => x.FromState.Equals(state) && !x.FromState.Equals(x.ToState)); if (transitionsForThisState.ToArray().Count() == 0) { return(0); } int nextCount = 0; foreach (Transition <T> transition in transitionsForThisState) { int returnedValue = CountNextState(newCount, transition.ToState); if (returnedValue == 0) { continue; } if (nextCount == 0) { nextCount = returnedValue; } else if (nextCount > returnedValue) { nextCount = returnedValue; } } return(nextCount); } }
private bool ExtractPath(string input, string state, ref Path path) { if (input.Length == 0 && FinalStates.Contains(state)) { path.Nodes.Add(state); return(true); } if (input.Length != 0) { var candidateInstructions = from ins in Instructions where ins.CurrentState == state && ins.Input == input[0] select ins; foreach (var instruction in candidateInstructions) { if (ExtractPath(input.Substring(1, input.Length - 1), instruction.NextState, ref path)) { path.Nodes.Insert(0, state); return(true); } } } return(false); }
/// <summary> /// Checks if by traversing the given transitions, then following all other empty transitions. /// </summary> /// <param name="givenTransitions">The transitions to check.</param> /// <returns>A boolean that is true if we can traverse an empty path.</returns> private bool CheckEmptyTransitions(IEnumerable <Transition <T> > givenTransitions) { bool foundEmptyTransitionToFinalState = false; //Check if we can jump to the final state foreach (Transition <T> transition in givenTransitions) { if (FinalStates.Contains(transition.ToState)) { foundEmptyTransitionToFinalState = true; } if (foundEmptyTransitionToFinalState) { break; } } //If not, try the other states or return when we can't traverse any further. if (!foundEmptyTransitionToFinalState) { List <T> newFromStates = new List <T>(); foreach (Transition <T> transition in givenTransitions) { newFromStates.Add(transition.ToState); } IEnumerable <Transition <T> > transitionsToCheck = Transitions.Where(x => x.Identifier == '$' && newFromStates.Contains(x.FromState)); if (transitionsToCheck.Count() <= 0) { return(foundEmptyTransitionToFinalState); } else { foundEmptyTransitionToFinalState = CheckEmptyTransitions(transitionsToCheck); } } return(foundEmptyTransitionToFinalState); }
public bool IsPossible(int index, string text, T state) { if (index == text.Length) { if (FinalStates.Contains(state)) { return(true); } return(false); } foreach (Transition <T> possibleTransition in GetTransition(state)) { if (possibleTransition.Symbol == text[index]) { if (IsPossible(index + 1, text, possibleTransition.ToState)) { return(true); } } } return(false); }
public bool CheckStr(string str) { var currentState = IntialState; foreach (var c in str) { if (States[currentState].Transitions.Keys.Contains(c)) { currentState = this.States[currentState].Transitions[c]; } else { return(false); } //if (index == -1) return false; //currentState = TransitionFunction[currentState][index]; } if (FinalStates.Contains(currentState)) { return(true); } return(false); }
protected StateFunction GetPossibleFunction() { StringBuilder sb = new StringBuilder(CurrentState); for (int i = 0; i < TapeAmount; i++) { sb.Append(Tapes[i].Read()); } var read = sb.ToString(); try { return(FunctionMap[read]); } catch (Exception) { if (FinalStates.Contains(CurrentState)) { return(null); } throw new TuringException(string.Format("Kann keine Übergangsfunktion für \"({0}, {1})\" finden.", CurrentState, read.Replace(CurrentState, ""))); } }
private bool Accepts(State currentState, string input, StringBuilder steps) { if (input.Length > 0) { var transitions = GetAllTransitions(currentState, input[0]); foreach (var transition in transitions) { var currentSteps = new StringBuilder(steps.ToString() + transition + "\r\n"); if (Accepts(transition.OutputState, input.Substring(1), currentSteps)) { return(true); } } return(false); } if (FinalStates.Contains(currentState)) { Log += ConsoleWriter.Success("Successfully accepted the input " + input + " " + "in the final state " + currentState + " with steps:\r\n" + steps); return(true); } return(false); }
public bool MakeStep() { Steps++; StringBuilder sb = new StringBuilder(); foreach (var tape in Tapes) { sb.Append(tape.Read()); } var read = sb.ToString(); var key = CurrentState + read; StateFunction fn; try { fn = FunctionMap[key]; } catch (Exception) { if (FinalStates.Contains(CurrentState)) { return(false); } throw new TuringException(string.Format("Kann keine Übergangsfunktion für \"({0}, {1})\" finden.", CurrentState, read)); } if (StepMode != StepModeEnum.Fast) { Tools.UpdateDiagram(FunctionMap.Values.ToList(), fn); } CurrentState = fn.NewState; fn.Used = true; if (StepMode != StepModeEnum.Fast) { wait(); } for (int i = 0; i < TapeAmount; i++) { Tapes[i].Write(fn.Write[i]); if (StepMode != StepModeEnum.Fast) { Tapes[i].Print(); } } if (StepMode != StepModeEnum.Fast) { wait(); } for (int i = 0; i < TapeAmount; i++) { Tapes[i].Move(fn.Movement[i]); if (StepMode != StepModeEnum.Fast) { Tapes[i].Print(); } } if (StepMode != StepModeEnum.Fast) { wait(); } return(true); }
public bool IsFinalState(State state) { return(FinalStates.Contains(state)); }
public bool IsFinalState(ail.net.parser.FsaState xi_state) { ail.net.framework.Assert.NonNullReference(xi_state, "xi_state"); return(FinalStates.Contains(xi_state.Id)); }
public void RemoveFinalState(ail.net.parser.FsaState xi_state) { ail.net.framework.Assert.NonNullReference(xi_state, "xi_state"); ail.net.framework.Assert.Condition(FinalStates.Contains(xi_state.Id), "FinalStates.Contains(xi_state.Id)"); FinalStates.Remove(xi_state.Id); }
public ail.net.parser.Fsa Nfa2Dfa() { // Conversion of an NFA into a DFA (subset construction) // ..................................................... // Input: An NFA N. // Output: A DFA D accepting the same language. // Operations: // e-closure(s) is the set of NFA states reachable from s on e-transitions alone. // e-closure(T) is the union of e-closure(r) for all r in T. // move(T, a) is the set of NFA states to which there is a transition on input a from some NFA state in T. // // set the start state to e-closure(s0) and unmark it. // While there is an unmarked state T in Dstates do // Mark T // For each input symbol a do // If U := e-closure(move(T, a)); // If U is not in Dstates then // Add U as an unmarked state to Dstates; // Dtran(T, a) := U; // End; // End; ail.net.parser.Fsa result = new ail.net.parser.Fsa(); ArrayList dfa_states = new ArrayList(); // build pseudo dfa ail.net.parser.FsaStateSet start_dfa_state = CalculateStateEclosure(StartState); start_dfa_state.Id = dfa_states.Count; start_dfa_state.Marked = false; dfa_states.Add(start_dfa_state); bool proceed = false; for (;;) { IEnumerator dfa_state_enum = dfa_states.GetEnumerator(); while (dfa_state_enum.MoveNext()) { ail.net.parser.FsaStateSet dfa_state = (ail.net.parser.FsaStateSet)dfa_state_enum.Current; if (!dfa_state.Marked) { dfa_state.Marked = true; foreach (ail.net.parser.FsaTransitionPredicate predicate in Predicates.Values) { if (predicate.Text != ail.net.parser.FsaTransition.kEpsilonPredicate) { ail.net.parser.FsaStateSet move_set = CalculateMove(dfa_state, predicate.Text); if (move_set != (object)null) { ail.net.parser.FsaStateSet pseudo_dfa_state = CalculateEClosureFromMove(move_set); if (pseudo_dfa_state != (object)null && pseudo_dfa_state.States.Count > 0) { ail.net.parser.FsaStateSet new_dfa_state = HasDfaCompoundState(dfa_states, pseudo_dfa_state); if (new_dfa_state == (object)null) { new_dfa_state = pseudo_dfa_state; new_dfa_state.Id = dfa_states.Count; new_dfa_state.Marked = false; dfa_states.Add(new_dfa_state); dfa_state_enum = dfa_states.GetEnumerator(); // reset iterator } if (!dfa_state.Transitions.Contains(dfa_state.Transitions.Count)) { ail.net.parser.FsaTransition transition = new ail.net.parser.FsaTransition(dfa_state.Transitions.Count, dfa_state.Id, new_dfa_state.Id, predicate.Text, predicate.SwitchChar, predicate.Context, predicate.Rank); dfa_state.Transitions.Add(transition.Id, transition); } } } } } proceed = true; } } if (!proceed) { break; } proceed = false; } // populate states and final states foreach (ail.net.parser.FsaStateSet dfa_state in dfa_states) { ail.net.parser.FsaState state = result.AddState(dfa_state.Id); ail.net.framework.Assert.NonNullReference(state, "state"); foreach (ail.net.parser.FsaTransition transition in dfa_state.Transitions.Values) { result.AddTransition(transition.Start, transition.End, transition.Predicate.Text, transition.Predicate.SwitchChar, transition.Predicate.Context, transition.Predicate.Rank); } ail.net.parser.FsaState final_state = null; foreach (ail.net.parser.FsaState tmp_state in dfa_state.States.Values) { if (FinalStates.Contains(tmp_state.Id)) { ail.net.parser.FsaState org_state = (ail.net.parser.FsaState)States[tmp_state.Id]; ail.net.framework.Assert.NonNullReference(org_state, "org_state"); if (final_state == (object)null || org_state.Token.Priority > final_state.Token.Priority) { final_state = org_state; } } } if (final_state != (object)null) { result.AddFinalState(state, final_state.Token); } } result.StateCounter.Reset(States.Count); return(result); }