r/dailyprogrammer • u/XenophonOfAthens 2 1 • Aug 03 '15
[2015-08-03] Challenge #226 [Easy] Adding fractions
Description
Fractions are the bane of existence for many elementary and middle-schoolers. They're sort-of hard to get your head around (though thinking of them as pizza slices turned out to be very helpful for me), but even worse is that they're so hard to calculate with! Even adding them together is no picknick.
Take, for instance, the two fractions 1/6 and 3/10. If they had the same denominator, you could simply add the numerators together, but since they have different denominators, you can't do that. First, you have to make the denominators equal. The easiest way to do that is to use cross-multiplication to make both denominators 60 (i.e. the original denominators multiplied together, 6 * 10). Then the two fractions becomes 10/60 and 18/60, and you can then add those two together to get 28/60.
(if you were a bit more clever, you might have noticed that the lowest common denominator of those fractions is actually 30, not 60, but it doesn't really make much difference).
You might think you're done here, but you're not! 28/60 has not been reduced yet, those two numbers have factors in common! The greatest common divisor of both is 4, so we divide both numerator and denominator with 4 to get 7/15, which is the real answer.
For today's challenge, you will get a list of fractions which you will add together and produce the resulting fraction, reduced as far as possible.
NOTE: Many languages have libraries for rational arithmetic that would make this challenge really easy (for instance, Python's fractions module does exactly this). You are allowed to use these if you wish, but the spirit of this challenge is to try and implement the logic yourself. I highly encourage you to only use libraries like that if you can't figure out how to do it any other way.
Formal inputs & outputs
Inputs
The input will start with a single number N, specifying how many fractions there are to be added.
After that, there will follow N rows, each one containing a fraction that you are supposed to add into the sum. Each fraction comes in the form "X/Y", so like "1/6" or "3/10", for instance.
Output
The output will be a single line, containing the resulting fraction reduced so that the numerator and denominator has no factors in common.
Sample inputs & outputs
Input 1
2
1/6
3/10Output 1
7/15Input 2
3
1/3
1/4
1/12Output 2
2/3Challenge inputs
Input 1
5
2/9
4/35
7/34
1/2
16/33Input 2
10
1/7
35/192
61/124
90/31
5/168
31/51
69/179
32/5
15/188
10/17Notes
If you have any challenge suggestions, please head on over to /r/dailyprogrammer_ideas and suggest them! If they're good, we might use them!
12
u/skeeto -9 8 Aug 03 '15 edited Aug 03 '15
C. The result is instantaneous for all inputs. Turns out it's not relevant for the challenge input, but I was careful to avoid operating larger numbers than necessary (avoiding overflow). The LCM of challenge input 2 exceeds a 32-bit int, so 64 bits was necessary.
Edit: Here's an informal Challenge Input 3 of 100 fractions that requires some care to get right (but can still be done with signed 64-bit integers).
And finally my code:
2
u/[deleted] Aug 03 '15 edited Aug 03 '15
I somehow wasn't able to make it plain-looking. It assumes the input is valid. Works for integers too.
OUTPUT:
2
u/XDtsFsoVZV Aug 08 '15 edited Aug 09 '15
C
I'm so proud of this; I spent hours racking my brain desperately trying to figure it out. However, it fails on large inputs like challenge input #2, and I need to figure out how to make the input method more like what the challenge asks for without little segfault goblins attacking me.
Challenge Output #2:
Yet everything else comes out right.
The code:
6
u/SexmanTaco Aug 03 '15
Python overriding __add__
2
u/cbarrick Aug 03 '15
Prolog
The program is very clean in Prolog. I implemented it as a list reduction. The full solution with all the machinery for reading input files is here.
11
u/lukz 2 0 Aug 03 '15 edited Aug 04 '15
Z80 Assembly
This is a solution to a simplified problem that will run on 8-bit computer Sharp MZ-800 with Z80 cpu. The simplifications are mainly in the limited size of the input and output data.
The input is always of the form X1/Y1 + X2/Y2. All of X1, X2 are 8-bit numbers in the range 0-255, Y1, Y2 are 8-bit numbers in the range 1-255. The output will be in the form Z1/Z2, where Z1, Z2 are 16-bit numbers in the range 0-65279.
The input has to be provided at memory addresses 1300h-1303h so that X1 is at memory address 1300h, Y1 at 1301h, X2 at 1302h and Y2 at 1303h. After the result is computed it is printed out in text form. I am using function at address 0012h in the built-in ROM which prints a single character to screen.
The program starts at address 1200h and is
119118 bytes long.Edit: Added more comments and made the program shorter by 1 byte :).
Example session computing 1/6 + 3/10, screenshot
Code:
5
u/narcodis Aug 03 '15
Java. Uses Euclidean Algorithm to find the GCD.
Output for Challenge 1:
Output for Challenge 2:
1
u/[deleted] Aug 03 '15 edited Aug 11 '15
Java
I wrote add, sub, mult, and div. The first line should be what op you want to use, followed with the rest of the input.
Edited to use longs instead of ints, since challenge input 2 was causing overflow issues.
Edited again to use an interface so that I'm not checking which op to run with each input line.
Outputs:
Input 1:
Input 2:
Challenge Input 1:
Challenge Input 2:
What I'd like to do:
Figure out how Java can do something like function pointers, so I can just point to the math function once, rather than checking the op string for each given fraction. Probably clean up some of the code too.-- Done1
u/AnnieBruce Aug 07 '15
I made some really dumb mistakes getting to this point. I mean, really dumb, like the shebang being on line two dumb.
But I realized something, and that made me dig into some Python stuff, that while basic, I didn't know very well yet. It all boiled down to realizing that this is just summing a list. So I just needed a Fraction class that could add to itself, and the sum() function would take care of the rest. This forced me to write a(somewhat) more complete Fraction class than is strictly necessary, but I did learn about fun stuff like radd, and I bothered to handle the file input this time.
There are a few bits that could be removed, a few spots I broke things down step by step so I could throw in print statements for debugging. Could probably reduce line count if I wanted to, and that might even be sensible, but I spent enough time on this, and I'd say I'm done.
Python 3, if the shebang doesn't make that obvious. 3.4.3, specifically, if you care about that.
1
u/n-d-r Aug 07 '15 edited Aug 07 '15
Here is my inefficient solution in Python. Also my first contribution to this subreddit. Also my first time defining my own Exception classes.
Challenge output 1:
Challenge output 2:
1
u/mrschool Aug 07 '15
My submission using C#, it takes an incredible long time to run but it works. I am new to C# and would appreciate any feedback.
https://gist.github.com/jagorski2/ca777436299d6bbc1cef
1
u/Fulgere Aug 12 '15
I was working on this intermittently, but it still took me stupid long to finish! Anyways, here is my first submission. I wrote it in Java and had, I will admit, a bit of fun. I look forward to contributing in the future. If anyone is still even looking at this thread (=P) any feedback is greatly appreciated!
1
u/juanchi35 Aug 23 '15
Python
3
u/snarkyxanf Aug 03 '15 edited Aug 03 '15
I'm actually curious whether it makes more sense to reduce the inputs to lowest terms, find the least common denominator, and then add and reduce again, or whether it makes more sense to just cross multiply and reduce once
The upside of reducing only at the end is you only have to reduce once, the downside is that the intermediate products may be much bigger for some inputs.
"Makes more sense" in this context could be any concern from asymptotic complexity to basic implementation issues.
Edit: in an attempt to provide the ugliest, most hackish solution, I have one that uses sed to mangle the input into a script that it pipes into dc. Admittedly my sed was badly written, and I could make a few more dc macros to make this less ugly, but here's what I have so far:
Challenge 1 output:
Challenge 2 output:
Edit 2:
There's something wrong with my code. Trying it on larger sequences, like 1/1 + 1/2 + ... + 1/100 I get the correct denominator (verified by Wolfram Alpha), but the wrong numerator. I might try fixing it later, but debugging my monstrosity seems like a bad use of time at the moment.
3
u/curtmack Aug 03 '15 edited Aug 03 '15
Haskell
Deliberately avoiding the use of the Ratio type. This particular
mainimplementation can work with batch input, i.e. you can concatenate all the example problems into one file and the program will output all of the solutions one at a time. It's not very smart at error handling though, so you'll get weird errors like "Prelude.read: no parse" if you don't line up the fraction count with the number of fractions you give.Here's the output for all four of the problems, in order:
Edit: Removed an unnecessary
@binding3
u/KeinBaum Aug 03 '15 edited Aug 03 '15
Scala
So I went a bit overboard and implemented a whole new number type
Fraction. You can choose the underlying data type so you can useFraction[Byte],Fraction[Int],Fraction[Long],Fraction[BigInt]... Whatever integral datatype you can find works.Fraction[Float]andFraction[Double]don't, because that doesn't make sense.As far as Scala is concerned, it treats
Fractionthe same as any other number datatype (e.g. you can callsumon a list of Fractions).Challenge outputs:
3
u/Godd2 Aug 04 '15
In Ruby:
input 1:
input 2:
2
u/Praetorius 1 0 Aug 03 '15
Quick and dirty C++
2
u/Trolldeg Aug 03 '15 edited Aug 03 '15
Python 3, hacky and really ugly solution but seems to get the correct results
Output:
2
u/kirsybuu 0 1 Aug 03 '15
D Language, fully lazy:
Challenge Outputs:
2
u/adrian17 1 4 Aug 03 '15 edited Aug 03 '15
J.
The cool thing about functional tacit approach is that J can generate an inlined oneliner for me:
2
u/crossroads1112 Aug 03 '15 edited Aug 03 '15
Python 2.6 to 3.4 (Could work for older versions. I don't know when
reducewas added to functools.)This program essentially just ignores the part of the input telling how many fractions there are because it doesn't matter. It will add as many fractions as are supplied to it (mostly thanks to reduce). You'd run it buy just supplying arguments (hence why I needed sys.argv) like so:
fractions.py 10 1/7 35/192 61/124 90/31 5/168 31/51 69/179 32/5 15/188 10/17Additionally, unlike some in this thread, this will work with whole numbers in the input as well.
Output: 351910816163/29794134720
2
u/fvandepitte 0 0 Aug 03 '15 edited Aug 04 '15
Haskell, Feedback is welcome
I didn't use
Data.FractionData.Ratiobecause that would have been easy.Output:
2
u/Wizhi Aug 03 '15
I've always hated fractions. I might just be lazy, but they're so bothersome.
A solution in C# with some more operators added because I needed to remind myself how to deal with fractions.
2
u/wizao 1 0 Aug 03 '15 edited Aug 03 '15
Haskell:
Using
Data.Ratio:2
u/a_Happy_Tiny_Bunny Aug 03 '15 edited Aug 03 '15
Haskell
Safe and short (no code-golfing though):
The program ignores the first line of the input (the number of lines/fractions to come). When reading a Fraction from a line, the function expresses that this operation might fail, and so the function might return a fraction. This is what the type
Maybe Fractionis for.In this particular implementation, malformed lines are simply ignored.
The Greatest Common Divisor algorithms is Euclid's, and its has an
'at the end because Haskell imports agcdfunction by default.Haskell Code Golf
Just for fun (unsafe in that it assumes well-formed input):
Character count: 167, including newlines
EDIT: Down to 165 characters thanks this comment by /u/wizao in which he uses
breakinstead ofsplinOn, which saves me an import statement (and some readability).2
u/Wiggledan Aug 04 '15
C89. I went for readability over trying to keep it short, works for both challenge inputs.
2
u/Rekumaru Aug 04 '15 edited Aug 04 '15
:)
Common Lisp:
If you wanted it to follow the input listed with the number of fractions we would take the rest of the list and reduce + on that, disregarding the number of items.
2
u/battleguard Aug 05 '15 edited Aug 05 '15
c# implementation
2
u/Flongsch Aug 06 '15
Used Java Im still very new to Java and programming at all, so its pretty bad. Furthermore the canceling of the fraction you get after adding does only work once. Im Open for advices. (Output lines and some variables are in german...) Anyways, heres my Code:
2
u/grangelov Aug 07 '15
Perl
3
u/glenbolake 2 0 Aug 03 '15
Python 2.7. Simple and straightforward. My local copies of the inputs lack the first line.
Challenge outputs:
3
u/Godspiral 3 3 Aug 03 '15
In J, cheating due to build in support for fractions
7r15
with sample input (including number 2) on clipboard
37r15
1
u/DownloadReddit Aug 03 '15 edited Aug 03 '15
C
I'm using linux, so ctrl+d to stop inputs, or it can take them from file. I asume windows can do something similar.
$ ./226e < input1
$ ./226e < input2
1
u/Hells_Bell10 Aug 03 '15
C++
1
u/MajorRisk Aug 03 '15 edited Aug 03 '15
Swift solution...advice welcome..the main logic is in equateFractions.
Input:
Output:
1
u/demonicpigg Aug 03 '15 edited Aug 03 '15
Solved in php, can be accessed at http://chords-a-plenty.com/AddingFractions.php
Challenge Solutions:
1
u/ashish2199 0 2 Aug 03 '15 edited Aug 05 '15
Here is my implementation where i tried solving by creating a class for fraction and created a method to add two fractions and a method to reduce fraction to proper form.
Code: ( Java )
Output:
Edit:
1
u/what_why_me Aug 03 '15
Python 3:
1
u/nguyening Aug 03 '15
C++ comments appreciated:
1
u/fvandepitte 0 0 Aug 03 '15 edited Aug 04 '15
C++, calculations are done instantaneous for given inputs. Feedback is still welcome
I tried using
recursionwith thegcdmethod, but I had an overflow everytime.1
u/steffiwilson Aug 03 '15
Java, solution on gist. I'm reducing the fractions to display the whole numbers separately if the numerator would be greater than the denominator in the answer.
My output for challenge 1 is :
My output for challenge 2 is:
1
u/ChazR Aug 03 '15 edited Aug 03 '15
Haskell. I used the built-in gcd function because there is a limit to how much I'm going to reinvent.
1
u/[deleted] Aug 04 '15 edited Jan 02 '16
1
u/lacraig2 Aug 04 '15
My solution in Java:
1
u/1lurker2lurkers Aug 04 '15
Written in Java. The bottom class is for speeding up IO, nothing fancy.
Challenge 1
Challenge 2
1
u/[deleted] Aug 04 '15
Go solution. Solves all inputs instantly. Reduces the answer as each addition takes place so that we don't have to deal with overflow for the challenge inputs.
1
u/[deleted] Aug 04 '15
...
1
u/PuercoPop Aug 04 '15
In Common Lisp one can use the reader to do the 'heavy' lifting. But I am unclear as to what is the input? Is is a file? queried interactively? The gist of the solution is
1
u/c4a Aug 04 '15
Node.js, quick and dirty.
I'm not sure if it solves the final challenge input because it hasn't finished running yet, but it solves the other three. I'll see if I can optimize the GCD function.
1
u/alisterr Aug 04 '15 edited Aug 04 '15
Java 8. I tried to do it kind of OOPy, with the class "Fraction" handling its stuff. The main method is only to process the input and display the results. I'll definitely use and expand the Fraction class for future uses :)
Uses the euclid algorithm to determine the greatest common divisor.
Edit: minor optimization to do the third challenge input suggested by skeeto :)
Output for the challenges is as follows:
Code:
1
u/Reverse_Skydiver 1 0 Aug 04 '15
I guess I'm late, but here's my solution.
1
u/milliDavids Aug 04 '15
Ruby
1
u/briaxdho Aug 05 '15
Java, feedback welcome.
1
u/XDtsFsoVZV Aug 05 '15
Python 3.4
Challenge #1:
Challenge #2:
1
u/bdforbes Aug 05 '15
Mathematica
1
u/vzaardan Aug 06 '15 edited Aug 07 '15
Elixir. Any suggestions welcome, as it doesn't feel entirely functional to me but not sure how to refactor.
And there's a mix task to handle the input:
Input 1:
mix fractions.add 5 2/9 4/35 7/34 1/2 16/33 => "89962/58905"Input 2:
mix fractions.add 10 1/7 35/192 61/124 90/31 5/168 31/51 69/179 32/5 15/188 10/17 => "351910816163/29794134720"1
u/PapaJohnX Aug 06 '15
Python 3
1
u/jErler_dp Aug 06 '15
C++
First time, comments are obviously appreciated :)
I had to copy&paste the method to convert the input string to the fractions (more or less) from /u/nguyening since I am still pretty nooby. But besides that it went pretty smooth.
Outputs
1
u/aisas Aug 06 '15
My first attempt using Scala. Love to get some feedback :)
1
u/Scruptus Aug 07 '15
Solution in C# using linq, and some of the new stuff in C#6
Challenge output:
1
u/Blossberto Aug 07 '15
Python 2.7
1
u/hellectric Aug 07 '15
Groovy.
Created as a new Number implementation.
Cheating a little bit by using BigInteger.gcd instead of implementing it myself.
Output:
1
u/RustyJava Aug 07 '15
Java
Outputs:
1
u/Heretar Aug 08 '15
Java. Suggestions welcome. I came up with this solution quickly so I'm sure there are some redundancies in it.
1
u/skav3n Aug 08 '15
Python 3 I copied reductor from Trolldeg, because my solution eat a lot memory ;d
Output2:
1
u/caseym Aug 08 '15
Python 3.4. Proud that I didn't give up on this one. Took me a while!
1
u/Paulo_Atreides Aug 08 '15
Python 2.7
First time posting, feedback is welcome!
1
u/python_man Aug 09 '15 edited Aug 09 '15
Python2.7.5 Feed back welcomed.This program will reduce the fraction as much as possible and then output the fraction with any whole numbers.
1
u/MrEzekial Aug 10 '15 edited Aug 13 '15
Python 2.7. First time attempting anything on this sub. I don't know if my output is correct.
output:
1
u/LemonPartyDotBiz Aug 12 '15
Python 2.7
1
u/MEaster Aug 12 '15 edited Aug 12 '15
I've done it in F#. I've not used F# before, so probably not idiomatic.
Results are
[Edit] Made the validity check during parsing less stupid.
1
u/drksk8tr66 Aug 13 '15
Hey Guys, this is my first try at coding something other then "Hello World" in Python.(3.4.1) I would really appreciate any feed back you may have for me! My Solution
1
u/giodamelio Aug 15 '15
Simple solution in es6
1
u/Gr3y4r34 Aug 17 '15 edited Aug 17 '15
Better late than never! Written in java:
1
u/[deleted] Aug 19 '15
I didn't think this one was very easy. But I'm also a beginner. So, here's my solution (Python):
1
u/[deleted] Aug 19 '15 edited Aug 19 '15
Python. I ignored the first number in the input and instead used a while loop, worked just fine for the hard example and finished quite fast. Also coopted the fractions gcd function.
First submission, feel free to critique!
1
u/Steve132 0 1 Aug 20 '15
Weird C++
1
u/__dict__ Aug 21 '15
Prolog.
A fair amount of this is reading input from stdin, but it seemed worth starting to learn that in prolog too.
1
u/pro_grammar88 Aug 21 '15
Here's my mediocre Java attempt
1
u/AnnieBruce Aug 22 '15
Because I have too much time on my hands, I pulled my old COBOL textbook off the shelf and wrote up another submission.
This is kind of a pain to use, it really should take file input(or at least some string processing to enable input of whole fractions as n/d strings) but I haven't touched COBOL before tonight since a couple college courses over 10 years ago, didn't want to dig in to that just yet. It probably violates all sorts of good sense, even when you get past using COBOL at all. But, it does work, and it's a language I don't see here often so why not throw it up?
Yes, global variables. No, there are no simple(for my level as a COBOL programmer, at least) ways around this.
Compiles with OpenCobol 1.1.0 on Ubuntu 14.04. Haven't tried on any other platforms, YMMV.
It's amazing how quickly some of this came back to me after so long.
1
u/[deleted] Aug 23 '15 edited Aug 23 '15
Python 2.7. Feedback is welcome. New to python after mostly functional languages...
Output:
1
u/AnUntakenName Aug 25 '15 edited Aug 25 '15
In MATLAB, to avoid actually solving the problem:
And to make it a two-liner with some stupid indexing and linear algebra:
This abuses output formatting in MATLAB. It doesn't actually calculate the actual reduced fraction from summing the input, it just takes the decimal precision value of the variable and converts it to a fraction. So it won't work on the challenge inputs.
And for a real answer, here's one in C:
1
u/aw_ambir Aug 27 '15
Clojure
It's pretty darn slow, but it runs
1
u/nottwake Aug 29 '15
first time here... python 3.4
for 1st problem,
89962/58905
for 2nd problem,
most people got ---> 351910816163/29794134720
i got 2920947751856941/247298766709680
1
u/jpcf93 Sep 04 '15
Python3, instantaneous output for the toughest one. Since I am learning Python, I decided to go all OOP on it, and I think I looks neat :)
1
u/[deleted] Sep 04 '15 edited Sep 04 '15
Fortran... Copied a really nice gcd function from Rosetta code. Nothing special about the rest of my code, really. This was coded, compiled, and tested using cctools for android on my moto x. (Now if I could just get emacs or even just vi on this thing, that would rock!)
The program overflows on the optional challenge somebody posted, so I've probably missed a trick somewhere.
And here's the output...
1
u/xylotism Sep 05 '15
Ruby:
Outputs:
1
u/ullerrm Sep 10 '15
C++ -- decided to go crazy with this one and actually implement a complete fraction library, templated on the int type for numerator/denominator. Could basically copy-paste this "basic_fraction" class into a header and use it as if it was an STL class.
https://github.com/ullerrm/daily-programmer/blob/master/226easy/add_fractions.cpp
1
u/derokorian Sep 13 '15
Did it in PHP. The second challenge takes about 3 seconds, so there obviously room for improvement.
And the code that works it. I would love feedback on what I can do to improve it.
1
u/Ruftian Jan 18 '16
Novice Programmer here! This is my first post to r/dailyprogrammer I am hoping to keep building knowledge. I have rummaged through the past couple months of challenges and decided to start here. I used JAVA for this solution. I would love to hear any feed back that you all could give me!
Fractions.java
Utils.java
Output of Challenge 1:
Challenge 2 Output: (This isn't correct for some reason)
0
u/brickfire Aug 04 '15
My solution in java:
Probably should have used more OO principles while doing this, but considering my java knowledge is based mostly on this I half-remember doing about a year ago, this was relatively simple to do.
Also added a mixed-fraction conversion method to soothe my OCD.
0
u/[deleted] Aug 03 '15
[deleted] — view deleted comment
0
u/[deleted] Aug 19 '15
[deleted] — view deleted comment