text: Find all possible outcomes of a given expression | Utility function to eval1uate a simple expression with one operator only . ; This function eval1uates all possible values and returns a list of eval1uated values . ; To store result ( all possible evaluations of given expression ' expr ' ) ; If there is only one character , it must be a digit ( or operand ) , return it . ; If there are only three characters , middle one must be operator and corner ones must be operand ; every i refers to an operator ; l refers to all the possible values in the left of operator ' expr [ i ] ' ; r refers to all the possible values in the right of operator ' expr [ i ] ' ; Take above eval1uated all possible values in left side of ' i ' ; Take above eval1uated all possible values in right side of ' i ' ; Calculate value for every pair and add the value to result . ; Driver Code
code: < ? php function eval1 ( $ a , $ op , $ b ) { if ( $ op == ' + ' ) return $ a + $ b ; if ( $ op == ' - ' ) return $ a - $ b ; if ( $ op == ' * ' ) return $ a * $ b ; } function eval1uateAll ( $ expr , $ low , $ high ) { $ res = array ( ) ; if ( $ low == $ high ) { array_push ( $ res , ord ( $ expr [ $ low ] ) - ord ( ' 0 ' ) ) ; return $ res ; } if ( $ low == ( $ high - 2 ) ) { $ num = eval1 ( ord ( $ expr [ $ low ] ) - ord ( '0' ) , $ expr [ $ low + 1 ] , ord ( $ expr [ $ low + 2 ] ) - ord ( '0' ) ) ; array_push ( $ res , $ num ) ; return $ res ; } for ( $ i = $ low + 1 ; $ i <= $ high ; $ i += 2 ) { $ l = eval1uateAll ( $ expr , $ low , $ i - 1 ) ; $ r = eval1uateAll ( $ expr , $ i + 1 , $ high ) ; for ( $ s1 = 0 ; $ s1 < count ( $ l ) ; $ s1 ++ ) { for ( $ s2 = 0 ; $ s2 < count ( $ r ) ; $ s2 ++ ) { $ val = eval1 ( $ l [ $ s1 ] , $ expr [ $ i ] , $ r [ $ s2 ] ) ; array_push ( $ res , $ val ) ; } } } return $ res ; } $ expr = "1*2 + 3*4" ; $ len = strlen ( $ expr ) ; $ ans = eval1uateAll ( $ expr , 0 , $ len - 1 ) ; for ( $ i = 0 ; $ i < count ( $ ans ) ; $ i ++ ) echo $ ans [ $ i ] . " STRNEWLINE " ; ? >