", "var3", "var4"], ["==" /> ", "var3", "var4"], ["==" /> ", "var3", "var4"], ["=="/>

convert a prefix expression to infix expression using javaScript

1.5k Views Asked by At

I am really struck with a question .

convert the below expression using javaScript

[ "AND", ["<", "var1", "var2"], [ "OR", [">", "var3", "var4"], ["==", "var5", "var6"] ]

to

var1 < val2 AND (var3 > val4 OR val5 == val6)

Sorry that, I dont have any more informations

5

There are 5 best solutions below

0
sanil sathyan On

Try this..

function rpn( input ) {
   var ar = input.split( /\s+/ ), st = [], token;
   while( token = ar.shift() ) { 
     if ( token == +token ) {
        st.push( token );
     } else {
        var n2 = st.pop(), n1 = st.pop();
        var re = /^[\+\-\/\*\>\<\==\.]$/;
        if( n1 != +n1 || n2 != +n2 || !re.test( token ) ) {
            throw new Error( 'Invalid expression: ' + input );
        }
        st.push( eval( n1 + token + ' ' + n2 ) );
     }
   }
   if( st.length !== 1 ) {
      throw new Error( 'Invalid expression: ' + input );
   }
   return st.pop();
}
0
Mark Hannrey On

You can try below Syntax:

if ((var1 < var2) AND (var3 > var4 OR var5==var6))
1
Vishnu S Babu On

Try with this below mentioned Algorithm

  1. Accept a prefix string from the user.

  2. Start scanning the string from right one character at a time.

  3. If it is an operand, push it in stack.

  4. If it is an operator, pop opnd1, opnd2 and concatenate them in the order (opnd1, optr, opnd2).

  5. Push the result in the stack.

  6. Repeat these steps until arr of input prefix string ends.

  7. Pop the remaining element of the stack, which is the required Infix notation equivalent to a given Prefix notation.

0
Nishant Desai On

try this recursive approach

var convert = function(arr) {
    if (typeof arr[0] == 'string' && arr[1] instanceof Array && arr[2] instanceof Array) {
        return ' (' + convert(arr[1]) + arr[0] + convert(arr[2]) + ') ';
    } else {
        return ' ' + arr[1] + ' ' + arr[0] + ' ' + arr[2] + ' ';
    }
}
0
Usama Shahid On
Here is the simple example I did

// ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6


// If operator pop two numbers
// If number add it into stack

// 4 -> Add to stack
// 13 -> Add to stack
// 5 -> Add to stack
// / -> 13 -> a and 5 -> b (13 / 5) -> add to stack
// + -> 4 + (13 / 5)


const reverseTo = ["4", "13", "5", "/", "+"];

var stack = [];

var operators = ["+", "-", "/" , "*"];

function operation(a,b, operator){
  
  switch(operator){
    case '+':
      return a+b;
    case '/':
      return a/b;
    case '*':
      return a*b;
     case '-':
      return a-b;
  }
}


reverseTo.map(item => {
  
  if(operators.includes(item)){
       
    b = stack.pop();
    a = stack.pop();
    
    var output = operation(parseInt(a),parseInt(b),item);
//     console.log(b,a,output, item)
    stack.push(output);
    
   }else{
     stack.push(item);
   }
});

console.log(stack);