Converting Infix to prefix notation in JavaScript

别说谁变了你拦得住时间么 提交于 2020-01-06 05:26:18

问题


(I did ask a similar question in the past, but the documentation was wrong, so this is the correct version of that past question)

Please help me in JavaScript: The program that I am coding is one that takes in an expression in prefix notation and outputs the same expression in infix notation. The idea behind this program is as follows:

if the user enters + 1 2 the expected output is 1 + 2. All valid symbols are +, -, *, /, and %. The amount of numbers that the user can enter should be limitless (so for example, if I enter + + + + + + + + + 1 2 3 4 5 6 7 8 9 10, the program should return 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10).

Could someone please help me fill in the comment out portion of the loop, and if you think there's a better approach to the problem entirely, I am open to that!

function infix(input) {
  var x = input.split(''); // splits each variable and stores it in an array
  var output = [];
  var final = " "; // will be used to store our infix expression
  for (var i = 0; i < x.length; i++) {
    //if x[i] is any of the following : "+, -, *, /, or %" , store it in array output at index 0
    //else if x[i] is a number : store it in an index of array output that is >= 1

  }
  for (var j = 0; j < output.length; j++) {
    var final = x[0] + x[j];
  }
  console.log(final);
}

infix("1 + 2 + 3") // should output "+ + 1 2 3"
infix("1 - 2 % 3 + 1 * 4") // should output "- % + * 1 2 3 1 4"

回答1:


Your code is mostly there.

The main logic of your program needs to split your input string into two sections (arrays). One for symbols/operands, and another for numbers. Checking if x[i] is "+, -, ..." will allow us to check if the current symbol is an operand, which is a good start. However, we don't want to store it at index 0 of the output array. If you did this, then all of the symbols would be inputted in reverse order (which isn't what you want). Instead, you can add your symbols to the end of your array. In the code snippet below, I have pushed all symbols into the operands array.

So, how can we check if x[i] is a symbol? One way is to check x[i] against every symbol like so:

if(x[i] === "+" || x[i] === "-" || ... ) {
  operands.push(x[i]); // add the symbol to the end of the array  
}

Or, you could write this a little more cleanly using .includes(), which removes the need to multiple ||:

var symbols = ['+', '-', '*', '/', '%'];
...
if(symbols.includes(x[i])) {
  operands.push(x[i]); 
}

If the current character (x[i]) isn't a symbol then it must be a number (as we split on spaces). So, you can then add an else, and push the current character into the numbers array.

After you've looped through all characters, you'll have an array of operands, in the order that they appeared in the input string, and an array of numbers, also in the order they appeared in the input string. Our last step is to convert the operands and numbers array into strings, where each element in these arrays are separated by a space. The easiest way to do this is by using the .join() method, which will join every element in your array into a string, separating each element by the argument you give it.

By doing all of this, you can get your desired output:

function infix(input) {
  var x = input.split(' '); // splits each character and stores it in an array
  var operands = [];
  var numbers = [];
  var symbols = ['+', '-', '/', '*', '%'];

  for (var i = 0; i < x.length; i++) {
    if(symbols.includes(x[i])) {
      operands.push(x[i]);
    } else {
      numbers.push(x[i]);
    }
  }
  var final = operands.join(' ') +' ' +numbers.join(' ');
  return final;
}

console.log(infix("1 + 2 + 3")); // "+ + 1 2 3"
console.log(infix("1 - 2 % 3 + 1 * 4")); // "- % + * 1 2 3 1 4"

Or, you can do this more concisely by using the .match() method to get the non-numeric (or space) characters and another to get the numeric characters:

const infix = input =>
   [...input.match(/[^\d\s]/g), ...input.match(/\d+/g)].join(' ');

console.log(infix("1 + 2 + 3")); // "+ + 1 2 3"
console.log(infix("1 - 2 % 3 + 1 * 4")); // "- % + * 1 2 3 1 4"


来源:https://stackoverflow.com/questions/59131763/converting-infix-to-prefix-notation-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!