|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
a algorithm to validate an arithmetic expression
can anyone help me with this problem, any help will be appreciated. Basically I need to write an algorithm to validate an arithmetic expression such as 7 * ( 23 - 105 / 15 ) - 19.
The validate Method Examination of typical (valid) arithmetic expressions shows that if there are parentheses then they must appear in pairs, as ( ... ), and ( must be immediately before a number and ) must be immediately after a number, apart from parentheses a valid arithmetic expression is a sequence of numbers with one operator symbol between successive numbers. A 2-state FSA (Finite State Automaton) is the obvious device to use. The process is in state 0 when a number or ( be expected i.e. at the start of an expression or following an operator or following (. The process is in state 1 when an operator or ) could be accepted e.g. following a number The FSA should be in state 1 at the end of a valid expression (see attachment). If u want more explaination please ask. I'm new to algorithms so I'm having difficulty gettin my head around them. Thanks |
|
#2
|
|||
|
|||
|
An FSA won't cut it because you can nest parentheses. In fact, there's no FSA that accepts all of the following (which are valid):
(1+1) ((1+1)) (((1+1))) ((((1+1)))) ... and only accepts well-formed expressions. (If it accepted all of the above, then since it only has a finite number of states, by the pigeonhole principle, you can construct an expression (((...(((1+1)))...))) (n left parens, n right parens); where there are some k,j<n such that k != j but the FSA is in the same state after reading k left parens as after reading j left parens, so since it accepts this expression, it must accept the expression you get by deleting the left parens from k+1 to j, which clearly isn't well-formed.) You won't get around this problem without some way to keep track of arbitrarily large integers. You could augment your FSA with an assignable integer variable (which can have an infinite number of states, so it's no longer an FSA) to keep track of parentheses; that's just one way to do it. |
|
#3
|
||||
|
||||
|
an ideea: you could use trees.
if it can be memorized into a tree it's valid, if not it's not. ![]() or you could try the polish form. sorry i can't write down an explanation. look them up on google. |
|
#4
|
|||
|
|||
|
Use stack and postfix evaulation.
4 + 10 * 7 / (5 * 3 + 4 * 6) + 4 * 10 7 / ( * 5 3 + 5 * 6) +4 is last to execute. |
![]() |
| Viewing: Dev Shed Forums > Programming Languages - More > Software Design > a algorithm to validate an arithmetic expression |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|