Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void AddEpsilonTransition(int left, int right)
- {
- pairStates temp;
- temp.leftState = left;
- temp.rightState = right;
- epsilonTransitions.Add(temp);
- }
- void AddTransition(int left, int right, char c)
- {
- Transitions.Add(left.ToString() + "," + c, right);
- }
- int newState()
- {
- this.numStates++;
- return this.numStates - 1;
- }
- bool isOperator(string expression, int i)
- {
- int num = 0;
- while(i - 1 >= 0 && expression[i-1] == '\\')
- {
- num++;
- i--;
- }
- return num % 2 == 0;
- }
- int findPar(string expression, int i)
- {
- int num = 0;
- for (; i < expression.Length; i++)
- {
- if (expression[i] == '(') num++;
- else if (expression[i] == ')') num--;
- if (num == 0) return i;
- }
- return -1;
- }
- pairStates convert(string expression)
- {
- List<string> selection = new List<string>();
- int numPar = 0;
- int j = 0;
- int i = 0;
- for (; i < expression.Length; i++)
- {
- if (expression[i] == '(' && isOperator(expression, i)) numPar++;
- else if (expression[i] == ')' && isOperator(expression, i)) numPar--;
- else if(numPar == 0 && expression[i] == '|' && isOperator(expression,i))
- {
- selection.Add(expression.Substring(j,i-j));
- j = i + 1;
- }
- }
- if (selection.Count() > 0) selection.Add(expression.Substring(j, i - j));
- int leftState = newState();
- int rightState = newState();
- if (selection.Count() > 0)
- for (i = 0; i < selection.Count; i++)
- {
- pairStates temp = convert(selection[i]);
- AddEpsilonTransition(leftState, temp.leftState);
- AddEpsilonTransition(temp.rightState, rightState);
- }
- else
- {
- bool prefix = false;
- int lastState = leftState;
- for (i = 0; i < expression.Length; i++)
- {
- int a, b;
- if (prefix == true)
- {
- prefix = false;
- char transition;
- if (expression[i] == 't') transition = '\t';
- else if (expression[i] == 'n') transition = '\n';
- else if (expression[i] == '_') transition = ' ';
- else transition = expression[i];
- a = newState();
- b = newState();
- AddTransition(a, b, transition);
- }
- else
- {
- if (expression[i] == '\\')
- {
- prefix = true;
- continue;
- }
- if (expression[i] != '(')
- {
- a = newState();
- b = newState();
- if( expression[i] == '$') AddEpsilonTransition(a,b);
- else AddTransition(a,b,expression[i]);
- }
- else
- {
- j = findPar(expression,i);
- pairStates temp = convert(expression.Substring(i+1,j-i-1));
- a = temp.leftState;
- b = temp.rightState;
- i = j;
- }
- }
- if (i + 1 < expression.Length && expression[i + 1] == '*')
- {
- int x = a;
- int y = b;
- a = newState();
- b = newState();
- AddEpsilonTransition(a,x);
- AddEpsilonTransition(y, b);
- AddEpsilonTransition(a, b);
- AddEpsilonTransition(y, x);
- i++;
- }
- AddEpsilonTransition(lastState, a);
- lastState = b;
- }
- AddEpsilonTransition(lastState, rightState);
- }
- pairStates temp2;
- temp2.leftState = leftState;
- temp2.rightState = rightState;
- return temp2;
- }
Add Comment
Please, Sign In to add comment