Find all possible outcomes of a given expression | Utility function to evaluate a simple expression with one operator only . ; This function evaluates all possible values and returns a list of evaluated 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 evaluated all possible values in left side of ' i ' ; Take above evaluated all possible values in right side of ' i ' ; Calculate value for every pair and add the value to result . ; Driver program
function eval ( a , op , b ) { if ( op == ' ' ) { return a + b ; } if ( op == ' ' ) { return a - b ; } if ( op == ' ' ) { return a * b ; } return Number . MAX_VALUE ; } function evaluateAll ( expr , low , high ) { let res = [ ] ; if ( low == high ) { res . push ( expr [ low ] - ' ' ) ; return res ; } if ( low == ( high - 2 ) ) { let num = eval ( expr [ low ] - ' ' , expr [ low + 1 ] , expr [ low + 2 ] - ' ' ) ; res . push ( num ) ; return res ; } for ( let i = low + 1 ; i <= high ; i += 2 ) { let l = evaluateAll ( expr , low , i - 1 ) ; let r = evaluateAll ( expr , i + 1 , high ) ; for ( let s1 = 0 ; s1 < l . length ; s1 ++ ) { for ( let s2 = 0 ; s2 < r . length ; s2 ++ ) { let val = eval ( l [ s1 ] , expr [ i ] , r [ s2 ] ) ; res . push ( val ) ; } } } return res ; } let expr = " " ; let len = expr . length ; let ans = evaluateAll ( expr , 0 , len - 1 ) ; for ( let i = 0 ; i < ans . length ; i ++ ) { document . write ( ans [ i ] + " " ) ; }