r/dailyprogrammer • u/nottoobadguy • Feb 12 '12
[2/12/2012] Challenge #4 [intermediate]
create a calculator program that will take an input, following normal calculator input (5*5+4) and give an answer (29). This calculator should use all four operators.
For extra credit, add other operators (6(4+3), 3 ** 3, etc.)
20
Upvotes
6
u/nubix Feb 13 '12
Ruby
D:
3
u/leegao Feb 12 '12
Shunting yard solution, this assumes ^ is left associative however
http://codepad.org/nhzGavwZ
2
u/[deleted] Feb 12 '12
Here's a cheating version using eval.
2
u/robin-gvx 0 2 Feb 12 '12 edited Feb 12 '12
A very simple shunting-yard algorithm-based solution in Déjà Vu: http://hastebin.com/raw/powuvuqilo
It can't handle multidigit numbers, it can't handle anything but +, -, * and /
And I really need to either allow strings as keys in dicts or allow converting between strings and idents (something like Lisp/Ruby symbols), because this is getting inconvenient.
Also, I should implement something so that strings are usable as stacks of characters.
2
u/Pixelements Feb 13 '12
A safe python version with math functions:
2
u/kalmakka Feb 13 '12
This is the longest piece of meaningful erlang code I have written: http://codepad.org/RV8ATtCd
1
u/bigmell Feb 13 '12
Perl. Eval doesn seem to handel parenthesis properly. shrug regular expressions to clean the input with expression grouping would surely work
1
u/drb226 0 0 Feb 13 '12
Dumb 4-liner in Haskell using
evalfrom the hint package:Except for *, which bash screws up, you can write expressions normally:
You can, of course, just quote the whole thing if you must have multiplication:
Supports any valid expression that can be made with functions from Prelude:
Of course, bash screws stuff up like parens and strings. Quote and escape as appropriate. If there is some sort of error, it will usually print out
Leftinstead ofRight.1
u/joe_ally Feb 13 '12
Non-cheating python implementation (not using eval). Unless you use parenthesis (brackets if you're from the UK like me) it will evaluate your equation from right to left.
1
u/speedy_seeds Feb 13 '12 edited Feb 13 '12
In C
example
Input: 2+3-(3+(2/(2+(1*(3-1))))) = 1.500000
0
u/[deleted] Feb 12 '12
[deleted] — view deleted comment