Given an expression: 2 + ( ( 4 + 6 ) * (9 - 2) - 5 - 1) + 1 Write a program to calculate

24 views
Skip to first unread message

Qiangsheng Wang

unread,
Jan 5, 2015, 8:35:41 AM1/5/15
to rubyonra...@googlegroups.com
Given an expression:  2 + ( ( 4 + 6 ) * (9 - 2) - 5 - 1) + 1
1. Write a program calculate the given expression
2. Do not simply use "eval" directly
3. Need unit test

Bouns:
2 + ( ( 4 + 6 ) * sqrt(5) + 3) / 2  + 1

Here is my code, who can improve this for me? Thank you!
Here is test code.

Jason Fleetwood-Boldt

unread,
Jan 5, 2015, 10:34:34 AM1/5/15
to rubyonra...@googlegroups.com
Without an "x" in that expression I would argue that you don't need (and shouldn't have) a unit test.

Now, if you add an "x" to that expression, then your unit test becomes "Given value of X is ___, the result is ___" which makes a certain kind of sense.

But without an "x", all you're testing is Ruby's ability to parse, and C's ability to do math, which is certainly not within the scope of your use case or domain. 

Also I would argue that mathematically the part of the expression that reads (9 - 2) - 5 - 1 is ambiguous in terms of algebra since you need to know if the minus operation is "left order precedence" or "right order precedence". Personally I don't have time in my workday to remember that specific nuance of Ruby's implementation of algebra and if this were a Junior dev submitting a pull request I would make him or her add parenthesis to eliminate that confusion. 

Just my 2¢ on your post.  

-Jason


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/feeb4542-9acb-48d1-96e3-445e8a8ae9af%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

----

Jason Fleetwood-Boldt

All material © Jason Fleetwood-Boldt 2014. Public conversations may be turned into blog posts (original poster information will be made anonymous). Email ja...@datatravels.com with questions/concerns about this.

Dave Aronson

unread,
Jan 5, 2015, 10:36:38 AM1/5/15
to rubyonrails-talk
On Mon, Jan 5, 2015 at 8:35 AM, Qiangsheng Wang <wangq...@gmail.com> wrote:

> Given an expression: 2 + ( ( 4 + 6 ) * (9 - 2) - 5 - 1) + 1
> 1. Write a program calculate the given expression

Is this homework for school or an interview?

--
Dave Aronson, consulting software developer of Codosaur.us,
PullRequestRoulette.com, Blog.Codosaur.us, and Dare2XL.com.
Reply all
Reply to author
Forward
0 new messages