Jump to content
Sign in to follow this  
smus

Array into a formula

Recommended Posts

Elements of an array of a math formula look like this:

a = [1,'+',2,'-',3,'*',4,'/',5];

How do I perform all the arythmetic actions between those numbers. The array elements may be different, because they are added dynamically.

It would not be difficult if I didn't have to prioritize the actions (/,*,_,-). I tried using splice() method, but something goes wrong. Maybe I can somehow sort the elements according to the math actions priority?

Share this post


Link to post
Share on other sites

It's not simple, it requires a bit of thinking and work. The first step is to convert the current array to postfix notation. Once you're in a postfix notation, the algorithm to perform the calculation is simple.

Share this post


Link to post
Share on other sites

eval() works in this case, but I am not sure what the right priority is (operator precedence) in Javascript. Some websites has info that divistion(/) has the highest priority then goes multiplication, addition and subtraction. That is strange, because usually multiplication is the first.

1-2+3*4/5 = 1.4 according to JS compliler (/ then * then - then +, no idea why it counts like that)

1-2+3*4/5 = 1.6 according to Windows Calc (I guess, it counts without any priority)

1-2+3*4/5 = -3.4 if we use the correct operator precedence (* / + -)

What I was taught in high school is that the correct precedence must be: * / + - Never thought that there might be another order in programming languages.

Edited by smus

Share this post


Link to post
Share on other sites

Multiplication and division have the same precedence, addition and subtraction have the same precedence. When two operators of the same precedence are found, the leftmost operation is done first.

Share this post


Link to post
Share on other sites
13 hours ago, Ingolme said:

Multiplication and division have the same precedence, addition and subtraction have the same precedence. When two operators of the same precedence are found, the leftmost operation is done first.

Exactly, right. The precedence goes pair(* and /) over pair(+ and -) and the Win Calc must be set to a kind of formula mode to use precedence order, otherwise it counts numbers from left to right as they are. Thanks!

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
Sign in to follow this  

×
×
  • Create New...