r/dailyprogrammer • u/nint22 1 2 • Aug 12 '13
[08/13/13] Challenge #135 [Easy] Arithmetic Equations
(Easy): Arithmetic Equations
Unix, the famous multitasking and multi-user operating system, has several standards that defines Unix commands, system calls, subroutines, files, etc. Specifically within Version 7 (though this is included in many other Unix standards), there is a game called "arithmetic". To quote the Man Page:
Arithmetic types out simple arithmetic problems, and waits for an answer to be typed in. If the answer
is correct, it types back "Right!", and a new problem. If the answer is wrong, it replies "What?", and
waits for another answer. Every twenty problems, it publishes statistics on correctness and the time
required to answer.
Your goal is to implement this game, with some slight changes, to make this an [Easy]-level challenge. You will only have to use three arithmetic operators (addition, subtraction, multiplication) with four integers. An example equation you are to generate is "2 x 4 + 2 - 5".
Author: nint22
Formal Inputs & Outputs
Input Description
The first line of input will always be two integers representing an inclusive range of integers you are to pick from when filling out the constants of your equation. After that, you are to print off a single equation and wait for the user to respond. The user may either try to solve the equation by writing the integer result into the console, or the user may type the letters 'q' or 'Q' to quit the application.
Output Description
If the user's answer is correct, print "Correct!" and randomly generate another equation to show to the user. Otherwise print "Try Again" and ask the same equation again. Note that all equations must randomly pick and place the operators, as well as randomly pick the equation's constants (integers) from the given range. You are allowed to repeat constants and operators. You may use either the star '*' or the letter 'x' characters to represent multiplication.
Sample Inputs & Outputs
Sample Input / Output
Since this is an interactive application, lines that start with '>' are there to signify a statement from the console to the user, while any other lines are from the user to the console.
0 10
> 3 * 2 + 5 * 2
16
> Correct!
> 0 - 10 + 9 + 2
2
> Incorrect...
> 0 - 10 + 9 + 2
3
> Incorrect...
> 0 - 10 + 9 + 2
1
> Correct!
> 2 * 0 * 4 * 2
0
> Correct!
q
6
u/nint22 1 2 Aug 12 '13 edited Aug 12 '13
Sometimes you get it wrong, and have to rewrite a big part of your solution! Just happened to me, so don't let it discourage others from trying the challenge.
This is my initial attempt in C++, where I took a quick and hacky approach that works most of the time, but not all! The specific error here is that by not removing the elements that get multiplied together, adjacent add/subs incorrectly refer to the wrong result. A specific equation that I fail to compute for correctly is "0 + 6 * 7 * 7".
The more correct approach would of been to use an STL list, and pop out / replace the appropriate elements that get computed. I tried to avoid any sort of dynamic list, since that complicates code very quickly, but in this case it's almost needed (unless I take a polish-notation approach, but that is a big beefy solution to such a small challenge). I'll post that as soon as I'm done programming it.
Edit: Just re-wrote it with a different approach to the solution-computation..
7
u/[deleted] Aug 14 '13
Man, this challenge is harder than I thought.
I'm trying it in C++, and I can do it, but it ends up just being way longer than it should and just an abomination.
3
u/Rhinoceros_Party Aug 14 '13 edited Aug 14 '13
First time poster. Took 236 lines since I did some tricks to make it scalable. I got to use enums, and that's always fun. Critiques welcome. EDIT: Using Java.
13
u/Steve132 0 1 Aug 12 '13
Oddly succinct C++11
13
u/winged_scapula Aug 12 '13 edited Aug 18 '13
Python
Feast yer eyes:
EDIT: Code slightly changed on bluMyst suggestion. See the response bellow.
10
u/13467 1 1 Aug 12 '13
Ruby
9
u/shangas Aug 13 '13
Haskell
Handling operator precedence was the only slightly tricky thing in this one and I consider all solution that side-step the problem by using some form of "eval" to be cheating. ;)
(Except for the one which used C #defines to emulate "eval". That was very clever.)
8
u/skeeto -9 8 Aug 12 '13
JavaScript. Wanting to avoid cheating with
eval, it's messier than I had hoped. The tricky part isn't representing the expression as a data structure but printing it without any parenthesis, relying only on precedence.I skipped the interaction part, so here are some sample outputs:
7
u/Glassfish 0 0 Aug 13 '13
Python3:
7
u/JerMenKoO 0 0 Aug 13 '13 edited Aug 14 '13
python 3.x code-golfed:
6
u/BadArgumentHippie Aug 12 '13 edited Aug 20 '13
Adhering to the output description (not the sample I/O, tho ;)...
Edit: Typo.
6
u/[deleted] Aug 12 '13
My first DailyProgrammer challenge!
Java:
Although not very elegant, it does seem to work.
6
u/blimey1701 Aug 14 '13
Clojure! It took me a good long while to learn how to parse text and transform it into an AST ;)
4
u/MATTtheSEAHAWK Aug 14 '13
Excuse my language, but fuck me. I didn't see the no need for division. My punishment for skimming is my attempt to write this abomination: http://pastebin.com/yfms8G3f
I tried to do it without eval for fun, but that didn't work out. If it wasn't 12:45 and I didn't have work tomorrow, I would try it again, but not tonight. Tonight is for sleep.
4
u/killedbythegrue Aug 15 '13
Hello everyone, I just stumbled across this subreddit and had some time on my hands so have some Erlang.
And program output
3
u/DetectiveWoofles Aug 12 '13 edited Aug 12 '13
Python
EDIT: Fixed my original solution to fit in 80 chars per line.
3
u/Blackllama79 Aug 12 '13
It's in Java. Sort of. I'm a dirty cheater. Didn't feel doing the math calculation myself so used javascript's eval instead XD.
3
u/Garth5689 Aug 12 '13
Matlab
3
u/diosio Aug 13 '13
Second perl solution! Thanks to /u/microwavecookietime for his way of verifying the arguments :P
3
u/hamsolo474 Aug 13 '13 edited Aug 13 '13
Yet another python solution, its not pretty but it gets the job done. I might refine it a bit in the morning.
BTW since when is eval cheating!
P.S. I'm open to feed back this is my first submission, atm i am thinking of redefining number with a list comprehension (Inspired by /u/toodim, operators with a string (inspired by /u/missedtheplane), that whole output thing with format (inspired by /u/Glassfish)
3
u/[deleted] Aug 13 '13
Java
3
u/spacepotatoe Aug 14 '13
Not very elegant, and nowhere near as impressive as Maiddog's solution, but here is my working C solution :)
include <stdio.h>
3
u/CaptainCaffeine Aug 14 '13
Alright here's my code, written in python 3.3. Did it without using eval(), and also my first time posting a solution to dailyprogrammer, criticisms are welcome!
3
u/keithnorm Aug 14 '13
Implemented a really basic version of the shunting yard algorithm in C.
3
u/chunes 1 2 Aug 15 '13 edited Aug 15 '13
I hate this exercise. It took me hours and hours of hair-pulling to solve this.
Java:
3
u/Edward_H Aug 15 '13
My rather belated COBOL solution:
3
u/7f0b Aug 15 '13
Solution in PHP with comments and HTML form. I use eval to get the answer to equation, but equation is fully known and generated server side with no user input, so it should be safe.
3
u/mips32 Aug 16 '13
C99
2
u/toodim Aug 12 '13
Python 3
2
u/Dutsj Aug 12 '13
This was a bit tougher than it looked in C++11. It's the first challenge I'm taking part in. Took me a while, and I almost got it. I'll be working on the last 2 things tomorrow: having a q/Q exit instead of EOF, and having the operator precedence the right way. As of now it evaluates 0-1+2 as 0-(1+2) instead of the right way around. I'll have to rewrite the function that returns the answer, but I'm waaaay to tired to continue now. I've uploaded it here. Indentation is a bit wider than it's supposed to be on my text editor, but still quite readable I hope. I
2
u/TimeCannotErase Aug 13 '13
Here's my solution, written in R:
2
u/kirsybuu 0 1 Aug 13 '13
D Language. A bit long for the sake of being relatively extendable, mainly with fun template subclasses.
Sample Run:
2
u/nullmove 1 0 Aug 13 '13
Python 3
2
u/[deleted] Aug 13 '13
In python:
2
u/spfy Aug 13 '13
Java. Holy shit this was annoying. I originally started this with hundreds of switch/case statements. That was out of control; I managed to think it through a little better this way.
I keep getting Exceptions if I don't enter integers for input, everything I try is not helping. Still learning, I guess.
2
u/ThrowawayXTREME Aug 13 '13 edited Aug 13 '13
I did it in C#. Had to be a little creative. My first submission :) Looking forward to learning more.
2
u/Urist_Mc_George Aug 13 '13
And here my Python solution. One of my first Python programs.
2
u/Taunk Aug 13 '13
Added a few operators, which was actually pretty fun to play with.
Python:
2
u/hafela Aug 13 '13
It was actually quite fun. Any tip to check whether the input is transformable to int?
2
u/chrisledet Aug 14 '13
Ruby
2
u/PolarisDiB Aug 14 '13
Python 2.7. I had to look at other people's for some ideas, TIL eval() and how to prompt within a while loop:
Advice/criticism welcome, especially toward how to clean it up and make it shorter.
2
u/zengargoyle Aug 14 '13
A Perl programming language solution with a few neatos. Avoiding the easy out via
evalof the expression and instead abusing regular expressions (and theireval) to both create the equation and to solve it. An operator map that tracks precedence levels, a use of '·' MIDDLE DOT instead of 'x' or '*'. And using named block for theredo-ness of retrying answers and equations.A sample game...
2
u/[deleted] Aug 14 '13 edited Aug 15 '13
Here's mine in C++. It's probably incredibly verbose.
EDIT: I just now realized I could have put the random number generation into operator_char();...
EDIT 2: I just modified this slightly to make it more efficient.
2
u/luz_ Aug 14 '13
This one was tricky, Thought It would be easy but ended up spending many hours doing this, rewritingmy solution a couple of times when i thought i got everything wrong. Ended up with 114 lines in Java **Edit: not so experienced, but why not posting.
2
u/catchingExceptions Aug 14 '13
Perl, with some lines from /u/diosio
2
u/speakEvil Aug 15 '13
Yes, I know this is terrible. But on the other hand, I've learned quite a bit. Maybe I'll try to rewrite it after I sleep on it.
Common Lisp:
2
u/[deleted] Aug 15 '13 edited Aug 15 '13
Hooray for my first solution on /r/dailyprogrammer! I am also fairly new to pragramming, so any criticism is welcome. Without much ado, here is my solution in Python 3.2.2:
The only bug I noticed is that if you include 0 in the range of usable integers and it randomly gets placed after a divisor operator, the "divide by 0" error breaks the program. That andthere is nothing to keep the player from entering other invalid variables. But yeah, I think it works OK.EDIT: Whoops, removed division. Didn't see that it wasn't required.
EDIT2: Streamlined the input prompt after looking at some of the other python work
2
u/lukz 2 0 Aug 16 '13 edited Aug 18 '13
Common Lisp
The interesting part is the calculation of the correct value of the expression. We have eval() function in Common Lisp, but that requires an expression in prefix form while what we generate as the problem is an expression in an infix form. We thus need to program an evaluator for infix expressions.
2
u/brandnew3773 Aug 17 '13 edited Aug 17 '13
My java solution. Took about 75 lines. Critiques and criticisms are much appreciated. Also I don't understand why some people import the javascript eval function. That seems to take away all of the difficulty of solving this programming assignment.
}
2
u/bikko Aug 18 '13
This is my first submission to dailyprogrammer and one of my first Node.js programs!
Interesting parts:
Code:
Sample output:
2
u/htcorgasm 0 0 Aug 18 '13
An inefficient and wordy C# solution.
}
2
u/thisisnotmypenis Aug 19 '13
I finally manage to complete this thing, firstly I hacked up a version in C which didn't really work because of operator precedence, so I know I read about RPN, shunting yard and how it could be used for easy parsing with respect to operator precedence, the code is pretty messy just made it to work, but will revisit to make a proper parser.
[C++] https://gist.github.com/yippee-ki-yay/6269898
2
u/Smith7929 Aug 20 '13
Python solution using a class... just 'cause, I guess.
2
u/5hassay Aug 20 '13
you mean expression! :)
python33
2
u/Yamame Aug 22 '13 edited Aug 22 '13
Python2 solution with simple sanity check
I really appreciate your feedback :)
2
u/otsojaun Aug 23 '13
Java. A bit late to the party
2
u/[deleted] Aug 24 '13
F# with included unit test. I could've done the whole thing just using data table, like other dynamic languages (so one line basically), but it was more fun to generate the expression tree and evaluate it by hand.
Like the one haskell entry I saw here, I folded the expression tree to represent the order of operations.
I just realized I didn't really tie in the IO part of it, oops
2
u/MATTtheSEAHAWK Aug 24 '13 edited Aug 24 '13
Redid this one (python 3):
2
u/skyangelisme 0 1 Aug 25 '13
Python 2
It will regenerate a problem if the solution is NaN. Otherwise, nothing special; follows the problem description exactly.
2
u/thatusernameisalre Aug 26 '13 edited Aug 26 '13
My non-modular Ruby solution:
Edit: Original code didn't repeat expression on incorrect answer...oops!
2
u/134-IQ Aug 27 '13 edited Aug 27 '13
I'm late to the game, but this is an expandable C++ version. You can choose your range and your problem count.
2
u/pbl24 Aug 29 '13
Python and lambdas:
2
u/Amnestic Aug 31 '13 edited May 05 '26
Plot twist: this post no longer exists because Redact swept through and cleared it out along with everything else. Social media, messaging apps, people finder sites, all of it.
worm rob late act enter support license sink wipe oatmeal
2
u/nofingerpointing Sep 07 '13
My solution in Ruby 2.0.0. I had to peek into other questions for the eval trick :)
2
u/odhran666 Sep 10 '13
A Lua solution :
2
u/deathmangos Sep 15 '13
Better late than never. Used eval(), it was hard enough for me as it is. Javascript:
HTML:
2
u/dznqbit Sep 18 '13
Python github
2
u/vape Sep 18 '13
Very late but I'll submit it anyway. Python 3 solution with no error checking so I could keep the code short.
2
u/mentalorigami Sep 23 '13
Python 2.7 with a quick (and lazy) scoring system.
2
u/milliDavids Nov 06 '13
Python3
arithmetic_equation()
2
u/lets_see_exhibit_A Nov 06 '13
Java:
2
u/kate_katie_kat Nov 07 '13
Ruby
2
u/Hanse00 Nov 11 '13
Python 2.7
2
u/RangeruDangeru Nov 12 '13 edited Nov 12 '13
Not the best solution, but a solution. Definitely longer than I would have liked.
Python 3.3
2
u/luizpericolo Nov 13 '13
My python submission. I got lazy when I though of the possibility of writing an expression parser and eval() rocks. Maybe someone could create a slightly different version of this challenge on an intermediate level where the arithmetic expression can have paranthesis and any number of constants. (L Systems FTW)
2
u/VerifiedMyEmail Dec 10 '13 edited Dec 11 '13
JavaScript run in the console
1
u/bobjrsenior Aug 13 '13 edited Aug 14 '13
I made my solution in Java. It is pretty messy, but here it is. edit: Decided to add comments and refine the code a little.
1
u/pteek Aug 16 '13 edited Aug 16 '13
Here is my solution in C.
I spent one hour to think of a way to make the program exit only if q or Q is pressed. I can't figure out how to handle the input when the expected input is of two types and both can't be discarded until they are checked what they are.I am not very good with strings, so there might be a easy solution I missed.Okay, some reading helped and I have fixed the exit problem. Added and edited code is commented as such.
Please comment and provide your feedback.
Note: The commented printfs were used for early troubleshooting.
Output:
1
u/[deleted] Aug 16 '13
any tips on how to set order of operations preference in java?
1
u/TweenageDream Aug 17 '13 edited Aug 17 '13
I'm a bit late to the party but here is my solution in Ruby
1
u/roddz Oct 08 '13
My first attempt at one of these in java be gentle.
1
u/dabarnes Aug 13 '13 edited Aug 13 '13
java
I made this in high school for some project, not using the script engine... converts the equation to postfix and then does that math. It doesn't acutally do what the Daily programmer output asks but it has all the methods to do the math
edit: It also followed order of operations and handles ()'s and It was from my high school comp sci class, an android calculator.
1
u/Davess1 Aug 26 '13
quick python one: x = str(input(": ")) print(eval(x))
0
u/[deleted] Aug 12 '13
[deleted] — view deleted comment
0
u/[deleted] Aug 13 '13
[deleted] — view deleted comment
0
u/[deleted] Aug 23 '13
[deleted] — view deleted comment