Converting Infix To Prefix Notation In JavaScript
Solution 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"
Post a Comment for "Converting Infix To Prefix Notation In JavaScript"