Check if K can be obtained by performing arithmetic operations on any permutation of an Array | Function that finds the string of possible combination of operations ; If only one number left then check for result ; If resultant value is K ; Else return 0 ; Choose all combination of numbers and operators and operate them ; Choose the first two and operate it with ' + ' ; Place it to 0 th position ; Place ( n - 1 ) th element on 1 st position ; Evaluate the expression with current combination ; Now , we have N - 1 elements ; Try ' - ' operation ; Evaluate the expression with current combination ; Try reverse ' - ' ; Evaluate the expression with current combination ; Try ' * ' operation ; Evaluate the expression with current combination ; Try ' / ' ; Evaluate the expression with current combination ; Try reverse ' / ' ; Evaluate the expression with current combination ; Backtracking Step ; Return 0 if there doesnt exist any combination that gives K ; Function that finds the possible combination of operation to get the resultant value K ; Store the resultant operation ; Function call ; Given array arr [ ] ; Resultant value K ; Function call
function find ( v , n , dest , s ) { if ( n == 1 ) { if ( Math . abs ( v [ 0 ] - dest ) <= 0.0000001 ) { document . write ( s + ( dest ) . toString ( ) + " " ) ; return true ; } return false ; } for ( let i = 0 ; i < n ; i ++ ) { for ( let j = i + 1 ; j < n ; j ++ ) { let a = v [ i ] , b = v [ j ] ; let p = s ; v [ i ] = a + b ; v [ j ] = v [ n - 1 ] ; s = ( s + a . toString ( ) + ' ' + b . toString ( ) + " " ) ; if ( find ( v , n - 1 , dest , s ) ) return true ; s = p ; v [ i ] = a - b ; v [ j ] = v [ n - 1 ] ; s = ( s + a . toString ( ) + ' ' + b . toString ( ) + " " ) ; if ( find ( v , n - 1 , dest , s ) ) return true ; s = p ; v [ i ] = b - a ; v [ j ] = v [ n - 1 ] ; s = ( s + b . toString ( ) + ' ' + a . toString ( ) + " " ) ; if ( find ( v , n - 1 , dest , s ) ) return true ; s = p ; v [ i ] = a * b ; v [ j ] = v [ n - 1 ] ; s = ( s + a . toString ( ) + ' ' + b . toString ( ) + " " ) ; if ( find ( v , n - 1 , dest , s ) ) return true ; s = p ; if ( b != 0 ) { v [ i ] = a / b ; v [ j ] = v [ n - 1 ] ; s = ( s + a . toString ( ) + ' ' + b . toString ( ) + " " ) ; if ( find ( v , n - 1 , dest , s ) ) return true ; } s = p ; if ( a != 0 ) { v [ i ] = b / a ; v [ j ] = v [ n - 1 ] ; s = ( s + b . toString ( ) + ' ' + a . toString ( ) + " " ) ; if ( find ( v , n - 1 , dest , s ) ) return true ; } s = p ; v [ i ] = a ; v [ j ] = b ; } } return false ; } function checkPossibleOperation ( arr , k ) { let s = " " ; if ( ! find ( arr , arr . length , K , s ) ) { document . write ( " " ) ; } } let arr = [ 2 , 0 , 0 , 2 ] ; let K = 4 ; checkPossibleOperation ( arr , K ) ;