在 JavaScript 中将前缀转换为中缀

Converting prefix to infix in JavaScript

我正在尝试编写一个接受前缀表达式并输出中缀表达式的程序。我在下面列出了示例,以帮助证明我在说什么。我在下面粘贴了我的代码,有人可以帮我弄清楚如何在表达式中的两个数字之间移动符号吗?请参阅示例 1 以查看我尝试获取它的方法,但它不起作用。任何答案都会有所帮助或提示如何操作。感谢您的帮助!

/* The goal is to take in an expression in prefix notation and output it in infix notation
for example:
 + 1 2 outputs output 1 + 2
 + - 3 4 5 outputs 3 + 4 - 5
 % + / - 0 9 3 8 5 outputs 0 % 9 + 3 / 8 - 5 
*/

function convert(input){
  var x = input.split(''); // splits each variable and stores it in an array
  var output = "";
  // these are the valid symbols we can take, we will use these later
  var symbols = ['+', '-', '*', '/', '%'];
  // lets loop through all the values in x, starting at position 0
  for(var i = 0; i < x.length; i++){
    if(symbols.includes(x[i])) { // we hit a symbol, lets move it between 2 numbers
      /* now we need to figure out where to store the symbol. every 2 spaces starting at index 0
       we can insert a symbol (so spots like 1 3 5 7 etc). this loop will help us figure out what spot is empty
       , and it will store the symbol at that spot [see example 1 for a visualizaton]*/
      for(var j = 0; j < input.length; j+=2){
        if(output[j] == " "){
         // great, we can save the symbol here 
          output = output + x[i];
        }
      }
    }
    // otherwise we have a number on our hands
    else{
      output = output + x[i];
      console.log(output);
    }
  }
}

console.log(convert("+ 1 2"));

/*
example 1

if I have "+ 1 2"

+ is position 0
1 is position 2
2 is position 4

so the whitespace is at position 1 and 3. these are the spots where we can output the symbols
using the original expression + 1 2

position:  value:
-------- | ------
0        |    1
-------- | ------
1        |   " "
-------- | ------
2        |    +
-------- | ------
3        |   " "
-------- | ------
4        |    2

*/

只要你只使用简单的表达式,我建议将输入分成两个数组,数字和符号,然后将它们合并在一起。

var symbols = ['+', '-', '*', '/', '%'];

function convert(input) {
  var
    response = '',
    infixes = [],
    numbers = [];

  // Divide input into two arrays, infixes (or symbols) and numbers
  infixes = input.split(' ').filter(function(o) {
    if (symbols.includes(o)) {
      return true;
    } else {
      numbers.push(o);
    }
  });

  // Merge arrays
  for (let i = 0; i < numbers.length; i++) {
    if (infixes[i]) {
      response =
        response +
        numbers[i] + ' ' +
        infixes[i] + ' ';
    } else {
      response =
        response + numbers[i] + ' ';
    }
  }

  response = response.slice(0, -1);

  return response;
};

这个函数适用于你所有的例子,但如果你需要让它更智能,你可以在codepen上轻松修改和测试上面的函数here

function result_expression(expression, variables) {

    let opernads=['+','-','*','/'];

let arr=[...expression.split(" ")];



var len=arr.length;






while(len>0){

   
    let d1=arr[len-1]
    let d2=arr[len-2]
    let d3=arr[len-3]
 

    if(opernads.includes(d3)){

        if(isNaN(d2)){

            let tmp=variables[d2]
            d2=tmp;
        }
                if(isNaN(d1)){

            let tmp1=variables[d1]
            d1=tmp1;
        }

      
        let a=d2.toString().concat(d3).concat(d1)

       delete arr[len-1]
       delete arr[len-2]
       delete arr[len-3]


       let na=[];

       

       arr[len-3]=eval(a)

       arr.forEach(e=>{

        if(!(typeof e==='undefined')){

            na.push(e)
        }
       })

       arr=[...na]

console.log('arr',arr)

len=arr.length;

    // arr=[...newar]

    // len=arr.length
   
    }else{


        len--
    }

   
if(len==1){

    return arr[0]
}


}









}


//let expression="+ 6 * - 4 + 2 3 8";
//let expression="+ 6 * - 4 a b + 2 3 8";
let expression="+ * 6 5 3 2 2";





let variables={a:20,b:1}
let k=result_expression(expression, variables);

console.log('finalresult',k)