Shunting Yard algorithm in JS

output = prompt(“Enter the expression”);
//output = “9.78*23+(5/2)+(2*5)”

var result = [];
var str = “”;
var temp = [];
var expression = [];

//output =”66*(4-2)*5*(9/(5-2)*(6-5))”;

for (i = 0; i < output.length; ++i)

{

if(output[i] != "*" && output[i] != "+" && output[i] != "/" && output[i] != "-" )

temp.push(output[i]);

if(output[i] == "*" || output[i] == "+" || output[i] == "-" || output[i] == "/")

{
for(var j = 0; j<= temp.length-1 ; j++ )
{

if (temp[j] == '(' || temp[j] == ')')
{
expression.push(temp[j])
}
else
{
str += temp[j];
if (temp[j+1] == ")")
{ expression.push(str);
str = "";
}
}
}

var temp = [];
if (str!="")
{
expression.push(str);
}
expression.push(output[i]);

}

str = "";

}

for(var n = 0 ; n<= temp.length-1 ; n++ )
{
//expression.push(temp[n]);
if (temp[n] == '(' || temp[n] == ')')
{
expression.push(temp[n])
}
else
{
str += temp[n];
if (temp[n+1] == ")")
{ expression.push(str);
str = "";
}
}

}
if (str!="")
{
expression.push(str);
}

//alert(expression);
//output = "9.75+0.25*(16/(2+2))*2"

//==============================================================================
var output = [];
var stack = [];
var precedence = {'+': 1,'-': 1,'*': 2,'/': 2,'(': 0};

for(var i = 0; i precedence[stack[(stack.length -1)]])
{
stack.push(expression[i]);
}
else if((precedence[expression[i]] = 0 ; k–)
{
output.push(stack[k]);
stack.pop(stack[k]);
}
stack.push(expression[i]);
}
}

if(expression[i] == “)”)
{
for(var j = (stack.length-1); j > 0 ; j–)
{
if(stack[j]!=”(“)
output.push(stack[j]);
stack.pop(stack[j]);
}

}
}

//alert(stack)
if(i == expression.length-1 && expression[i] != “)”)
{
//alert(stack);
for(var j = (stack.length-1); j >= 0 ; j–)
{
if(stack[j]!=”(“)
output.push(stack[j]);
stack.pop();
}

}

}

//alert(stack);
for(var j = (stack.length-1); j >= 0 ; j–)
{
if(stack[j]!=”(“)
output.push(stack[j]);
}

//alert(output);

// Calculate the result

var result = [];

for (i = 0; i < output.length; ++i)
{
t = output[i];
//alert(t);
if (!isNaN(t))
result.push(t);
else if (t == "(" || result.length < 2)
return false;
else
{
//alert(result);
var rhs = result.pop();
//alert(rhs);
var lhs = result.pop();
// alert(rhs);
if (t == "+") result.push(parseFloat(lhs) + parseFloat(rhs));
if (t == "-") result.push(parseFloat(lhs) – parseFloat(rhs));
if (t == "*") result.push(parseFloat(lhs) * parseFloat(rhs));
if (t == "/") result.push(parseFloat(lhs) / parseFloat(rhs));
}
}
alert(result);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s