Mixed Number to an Improper Fraction

In this challenge you will be converting a mixed number to an improper fraction.

Because improper fractions use fewer numbers, your code will need to be as short as possible.

Examples

4 1/2
9/2

12 2/4
50/4

0 0/2
0/2

11 23/44
507/44


Specification

You may assume the denominator of the input will never be 0. The input will always be in the format x y/z where x,y,z are arbitrary nonnegative integers. You do not need to simplify the output.

This is so shortest code in bytes wins.

• You should add the tag "parsing". I'm sure most answers will spend more bytes on parsing the input and formatting the output than on doing the math.
– nimi
Dec 17, 2015 at 18:31
• Can the output be a rational number type or does it have to be a string? Dec 17, 2015 at 18:33
• @AlexA.: ... but a large part of the challenge. According to it's description the tag should be used in such cases.
– nimi
Dec 17, 2015 at 18:38
• Can x, y and z be negative? Dec 17, 2015 at 19:21
• Is the output format strict, or is the numerator on one line and the denominator on another line acceptable (i.e., instead of a / between, it's a newline)? Dec 18, 2015 at 13:39

LabVIEW, 29 LabVIEW Primitives

CJam, 1615 14 bytes

l'/']er~:Xb'/X


or

l'/']er~_@b'/@


Test it here.

Explanation

l      e# Read input.
'/']er e# Replace the "/" with a "]".
~      e# Evaluate the string as code. If the input was "i n/d", this pushes [i n] d.
:X     e# Store the denominator in X.
b      e# Treat [i n] as base-d digits. This effectively computes i*d + n.
'/     e# Push a slash.
X      e# Push the denominator.


The other version avoids using a variable by using a bit more stack shifting.

• I really need to start using base conversion in CJam more. Jul 13, 2017 at 7:15
• An alternate version: '//~\S/1$b'/@, this is 13 bytes. Edit: oh I forgot the input l. Jun 15, 2018 at 2:40 Mathematica, 58 bytes ToExpression@StringReplace[#," "->"+"]~ToString~InputForm&  This returns the simplified result. If outputting a rational number instead of a string is fine, we can save 19 bytes: ToExpression@StringReplace[#," "->"+"]&  PowerShell, 4744 42 Bytes Crossed out 44 is still regular 44 ;( $l,$n,$d=$args-split'\D';"$(+$l*$d+$n)/$d"


Golfed a couple bytes by using regex -split. Golfed a couple more thanks to TessellatingHeckler by swapping the regex.

The $args-split'\D' takes our input argument and splits on non-digit characters. Here it performs two splits, one on whitespace, the other on the / character. The results are then stored in the three variables using a simultaneous assignment. We then formulate the string output as (the $left number times the $denominator plus the $numerator) executed as a code block, a / slash, and then the $denominator again. • Hi, I think you can do -split ' |/' to save one character with a "match either this|or that" regex, or use -split '\D' to split on anything which isn't a digit and s(h)ave two characters. If @Downgoat is willing to be slightly flexible on the output format, '{0}*{2}+{1};{2}'-f($args-split'\D')|iex is 40 bytes and has much cooler output because the numbers are even one above the other! Dec 18, 2015 at 3:03
• @TessellatingHeckler Thanks for the regex assist. I've asked Downgoat for input. But $l,$n,$d=$args-split'\D';+$l*$d+$n;$d is shorter yet at 37, and logically follows the same pattern as here. Dec 18, 2015 at 13:48
• Oh yeah, just math! (That would be enough to beat a Perl answer, too) Dec 18, 2015 at 14:35

Java with Ten Foot Laser Pole 1.03, 79+25 (import) = 104 bytes

Requires import sj224.tflp.math.*;

String m(String[]a){return ""+new BigRational(a[0]).add(new BigRational(a[1]));}


This will almost certainly work with 1.04 as well, but so far I've only tested it with 1.03 because I already happened to have a java project set up with 1.03 in the build path.

JavaScript (ES6), 44 41 bytes

m=>([x,y,z]=m.match(/\d+/g),+y+x*z+"/"+z)


Saved 3 bytes thanks to @ETHproductions!

Explanation

Very simple.

m=>
([x,y,z]=m.match(/\d+/g), // x, y and z = numbers from input
+y+x*z                  // numerator
+"/"+z                  // denominator
)


Test

Test is without destructuring assignment to work in most browsers.

var solution = m=>+(p=m.match(/\d+/g))[1]+p[0]*p[2]+"/"+p[2]
<input type="text" id="input" value="11 23/44" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>

• Nice! You can use [p,q,r]= in place of p=, then replace p[0], p[1], and p[2] with p, q, and r, respectively. After this change, I get 41:m=>([p,q,r]=m.match(/\d+/g),+q+p*r+"/"+r) Dec 18, 2015 at 2:37
• @ETHproductions Thanks for the tip! I actually did consider using a destructuring assignment but they don't work in Chrome and I didn't have Firefox on hand to test it. :P Dec 18, 2015 at 3:03
• My first crossed out 44! :D Dec 18, 2015 at 3:04
• You can use m.split(/\W/g) instead to save a byte Jun 11, 2018 at 14:08

Japt, 10 bytes

Woohoo, currently beating CJam!

U*W+V+'/+W


Try it online!

How it works

       // Implicit: [U,V,W] = eval(input). This automatically discards the slash.
U*W+V  // Calculate the new numerator: (whole part * denominator) + numerator.
+'/+W  // Add the slash and the denominator.
// Implicit: output last expression

• I spent a good bit of time yesterday trying to figure out how I had earned 15 rep off of an answer, until I realized: my first green checkmark! \o/ Dec 21, 2015 at 22:40

Julia, 58 50 bytes

s->eval(parse((r=replace)(r(s," ","+"),"/","//")))


This is an anonymous function that accepts a string and returns a Rational type object. To call it, give it a name, e.g. f=s->....

We can take advantage of the fact that the input can be manipulated slightly to be an expression that evaluates to a rational. In particular, an integer plus a rational is a rational, and rationals are denoted with double slashes. So if we turn 4 1/2 into 4+1//2, the evaluated result will be 9//2.

Ungolfed:

function f(s::AbstractString)
# Replace the space in the input with a plus
r1 = replace(s, " ", "+")

# Replace the / with //
r2 = replace(r1, "/", "//")

# Parse the resulting expression as a rational
return eval(parse(r2))
end


Smalltalk – 76 characters

The input exactly matches the array delimiter and inherent fraction representation of Smalltalk. If it just weren't so verbose, it could have been a serious contender!

Compiler evaluate:'|p|p:=0.#(',FileStream stdin nextLine,')do:[:q|p:=p+q].p'


It's too bad simplification wasn't a requirement, Smalltalk does it automatically!

dc<<<${@/\// }sarla*+n47Plap  $@ expands to all command-line parameters, so ${@/\// } expands to all command-line parameters with / replaced with  , which is put on dc's stack. The rest is simple stack manipulation and arithmetic. 05AB1E, 17 15 bytes #'/¡RŠ©*+®'/ý  -2 bytes thanks to @MagicOctopusUrn. Explanation: # # Split input by spaces and push all items to the stack # i.e. "4 1/2" → "4" and "1/2" '/¡ # Push the second item by "/" # i.e. "1/2" → [1,2] R # Revert the list, and also push all items to the stack # i.e. [1,2] → [2,1] → 2 and 1 Š # Triple-swap the stack # [4,2,1] → [1,4,2] © # Store the 2 in the register * # Multiple the top two items # 4 and 2 → 8 + # Add the top two items # 1 and 8 → 9 ® # Push the 2 from the register to the stack again '/ý # Join the two items by "/" # 9 and 2 → "9/2"  With flexible input- and output-format, taking the integers in the order x,z,y and outputting the nominator and denominator on separated lines it would be 4 bytes (which is why I added the -tag to the challenge..): *+²»  Explanation: * # Multiply the first two inputs (x and z) # i.e. 4 and 2 → 8 + # Add the third input (y) # i.e. 8 and 1 → 9 ² # Take the second input again (z) » # Join the stack by newlines and implicitly print it  • @MagicOctopusUrn Thanks, but the input-format is different than in the challenge description. Apparently the format (as single string) 4 1/2 is mandatory for this particular challenge. Otherwise I would have used my 4-byte version (or if output was mandatory, but input flexible I would use this 6-byter: *+'/²J) Jun 15, 2018 at 13:02 • 15-bytes Jun 15, 2018 at 13:05 • @MagicOctopusUrn Oh, didn't even knew about "Push all the items of a into the stack".. o.Ô Exactly what I needed for this challenge! And smart with the join by "/". Thanks! :) Jun 15, 2018 at 13:16 • I hate using the "Push all items of a into the stack" command because it's "" and it can't be tamed by inline code-tags. Jun 15, 2018 at 13:17 • @MagicOctopusUrn yeah, it's also a bit annoying in comments (which is why I quoted "Push all the items of a into the stack" instead of using ''.. Jun 15, 2018 at 13:18 Haskell, 7467 63 bytes r=read f x|(a,(c,s:d):_)<-lex<$>lex x!!0=show(r a*r d+r c)++s:d


Try it online!

Explanation

As H.PWiz figured out we can use Haskell's lexer here to break up the string into it's parts. (Earlier I was using span(>'/')) And Laikoni pointed out that <$> works just like mapSnd from Data.Tuple. The pattern guard breaks up our code into the three numbers we want using lex. lex invokes haskell's lexer to break off the first token. It returns a list with each element representing a possible way to parse the string. These elements are tuples with the first element being the first token and the rest of the string being the second element. Now since the input format is very regular we are only ever going to have exactly one parse, so we can always take the first one. The first thing we do is invoke lex on the input lex x  Then we unwrap it from it's list giving us a 2-tuple lex x!!0  The first token will be the whole part of the mixed fraction leaving the fraction prepended by a space to still parse. Then since tuples are Functors we can use (<$>) an alias for fmap to apply lex to the second element of the tuple.

lex<$>lex x!!0  This eats through the space and breaks off the next token, the numerator of our fraction. Now we bind this to a pattern match using <-. Our pattern is (a,(c,s:d):_)  a grabs the whole part of the fraction, our first token. :_ unwraps the list resulting from our second lex. c grabs the second token we lexed, that is the numerator of the fraction. Everything that remains is bound to s:d which splits it into its first character, guaranteed by the format to be a / and the remainder which will be the denominator. Now that we have parsed the input we do the actual computation: show(r a*r d+r c)++s:d  Where r is the read function we bound earlier. It is important to note that lex returns a list empty if it fails and non-empty if it succeeds. Why this is not a Maybe I do not know. • 67 bytes Jun 15, 2018 at 2:01 • @H.PWiz That is a great use of lex. Jun 15, 2018 at 2:03 • 65 bytes: Try it online! Jun 15, 2018 at 5:19 • You should be able to save another 2 by matching on the / Jun 15, 2018 at 9:38 • 59 bytes Jul 9, 2018 at 5:17 Stax, 1 byte +  Run and debug it (although there's not much to debug) The challenge specification says "You do not need to simplify the output." Assuming it's allowed to simplify, then there's a built-in instruction in stax to do this. The input is implicitly interpreted as an integer and a rational number. The + instruction widens both to rationals, adds, and simplifies. The result is implicitly printed. Forth (gforth), 92 bytes : f 0 -rot 3. do 0 -rot >number 1 m+ loop 2drop + >r swap i * + r> <# 0 #s '/ hold + #s #> ;  Try it online! The pain of parsing and formatting... Takes a string as pointer length (gforth standard), and returns a string in the same format. How it works : f ( addr u -- addr u ) \ take a string and return a string 0 -rot \ ( 0 addr u ) 3. do \ repeat 3 times... 0 -rot \ ( ... 0 0 addr u ) >number \ ( ... num 0 addr u ) parse an integer; \ addr now points to right after the parsed int 1 m+ \ increment the addr to point to the next integer loop \ end loop ( x y z 0 addr u ) 2drop + \ discard input string and zero on the top >r \ ( x y R:z ) so the value of z can be copied by i swap i * + \ ( x*z+y R:z ) r> \ ( x*z+y z ) <# \ start formatting the output from the end 0 #s \ push z to the output; formatting built-ins take double cells '/ hold \ push a slash + #s \ #s leaves two zeros at the top, so discard one and push x*z+y #> \ finish formatting and get the string ( pointer length ) ;  Wolfram|Alpha, 0 or 1 byte =  The challenge says it's not necessary to simplify the output, but doesn't disallow it. If it's not disallowed, then: 1)The online Wolfram|Alpha interpreter will automatically convert mixed numbers to improper fractions (0 bytes). E.g.: 2)The Wolfram|Alpha interpreter can be called within Mathematica by entering = followed by the input (1 byte): Thunno 2, 18 bytes OẸ'//ẸsNṭẊ,p+x,'/j  Try it online! Explanation OẸ'//ẸsNṭẊ,p+x,'/j # Implicit input ("x y/z") OẸ # Split on spaces, then dump onto the stack '//Ẹ '# Split the fraction on "/", then dump again sN # Swap and convert the numerator to integer ṭ # Triple swap to get the order [y, x, z] Ẋ # Copy z to the register without popping ,p # Multiply x and z (implicit conversion to int) + # Add this to y (which we converted earlier) x, # Pair this with z (from the register) '/j '# Join this pair on "/" # Implicit output  Vyxal, 3 bytes ⌈E∑  Try it Online! -4 thanks to lyxal ⌈ # Split on spaces E # Evaluate each ∑ # Sum  • Try it Online! for 7 bytes Jul 17, 2021 at 11:51 • This doesn't seem to work anymore (no clue why, maybe it was a 2.5 build specific thing, it would have been valid at the time though.). Try it Online! works though, for 3 bytes. Aug 14, 2023 at 10:45 • @lyxal That doesn't work either, try 0 0/2 for instance Aug 14, 2023 at 10:54 • Husk does it too, so it seems to be allowable Aug 14, 2023 at 11:18 • As does the wolfram answer Aug 14, 2023 at 11:20 Factor, 43 bytes [ eval( -- x x ) + >fraction [I${}/${}I] ]  Attempt This Online! Assumes the input must be a string, otherwise this can be shorter. Simplifies the output. Javascript ES6, 62 bytes p=prompt;b=p(a=+p()).split/;alert((+b[1]*a+ +b[0])+"/"+b[1])  • Pretty nice! Some tips: You can use [b,c]= in place of b=, then use b in place of b[0] and c in place of b[1]. Also, you can rearrange the equation so you don't need parentheses at all: p=prompt;[b,c]=p(a=+p()).split/;alert(+b+c*a+"/"+c) Dec 18, 2015 at 2:32 Perl, 8261 38 bytes #!perl -paF/\D/$_=$F[0]*$F[2]+$F[1]."/$F[2]"


This can probably be golfed more.

Changes

• Saved 16 bytes by using a regex in split, and 5 by using <> instead of <STDIN>.
• Saved another 16 bytes thanks to Dennis.
• With shebang #!perl -paF/\D/ (9 bytes), you can use $_=$F[0]*$F[2]+$F[1]."/$F[2]". Dec 17, 2015 at 19:27 • @Dennis I've added that in. Thanks! Dec 17, 2015 at 19:33 • The #!perl part of the shebang and the linefeed do not count. This is only 38 bytes. Dec 17, 2015 at 19:35 • @Dennis Oh, OK. I'll correct it now. (On the bright side I think this is the second-shortest non-esoteric answer) Dec 17, 2015 at 19:37 Mathematica, 51 bytes Interpreter["ComputedNumber"]@#~ToString~InputForm&  Interestingly, Mathematica supports this with a built-in. If outputting a number is allowed, than we only need 28 bytes: Interpreter@"ComputedNumber"  Java, 159148142120 110 bytes String m(String[]a){Long b=new Long(a[0]),d=new Long((a=a[1].split("/"))[1]);return b*d+new Long(a[0])+"/"+d;}  Saved a bunch of bytes thanks to FlagAsSpam. • @FlagAsSpam Done. Dec 17, 2015 at 23:49 • @FlagAsSpam But then the variables will be left undeclared! Dec 17, 2015 at 23:50 • Disregard all of what I just said - a short way doing what you're doing is Long b=new Long(a[0]),c=new Long((a=a[1].split("/"))[0]),d=new Long(a[1]); Dec 17, 2015 at 23:55 Ruby, 23 bytes ->x{eval x.split*?++?r}  Try it online! ARBLE, 13 bytes a*c+b.."/"..c  Try it online! • I'm pretty sure the input format "x y/z" is mandatory for this particular challenge, but just in case I've asked OP to verify. Jun 15, 2018 at 13:05 Python 3, 78 76 bytes def f(s):a,b=s.split();b,c=b.split('/');return'%s/'%(int(a)*int(c)+int(b))+c  Try it online! • return'%s/'%(int(a)*int(c)+int(b))+c is 2 bytes shorter – ovs Jun 16, 2018 at 13:07 Perl 5 with -la -Mfeature=say, 32 bytes 25 bytes m|/|;say$_*$'+$F[1],"/$'"  Try it online! (-7 bytes thanks to Dom Hastings) $_ is the whole input x y/z, which evaluates the value of x in numeric contexts (like the * here). $' is the regex post-match string, which here contains whatever comes after / - so, z. To get the y value, we use the -a flag which splits the input on spaces and places them in the @F array. So here, @F = ("x", "y/z"), which means $F[1]="y/z" which evaluates in y in numeric contexts (since y is the initial contiguous sequence of digits with $F[1]). • You do not have to count the -p flag in your byte count; instead you count the language as Perl 5 with -p flag, 32 bytes. See this meta post for the current consensus. Jun 16, 2018 at 10:53 • Nice approach! I just had a little go at this and managed to make a 25 byte version: Try it online!. Using $' was the only real difference there really! Jun 21, 2018 at 20:48
• The combination of using both regex-$' and -a-$F[n] to get parts of the string is a pretty good idea, I have to remember that! Thanks, updated the post. Jun 22, 2018 at 13:42

Husk, 4 bytes

Σmrw


Try it online!

ṁrw is supposed to work, but there's some bug that returns an empty list. Anyway, hooray for native rational number support.

GNU AWK, 5+16 = 21 bytes

Command-line argument: -F |/

Source code:

$0=$1*$3+$2"/"\$3


Try it online!

The command-line argument sets the field separator to the regex / |\//. Thus, it is easy to map the input as three fields.

Itr, 1 byte

+

Itr has built-in support for rational numbers, including for parsing input numbers.

online interpreter

Explanation

   ; implicit input, by default numbers are separated by spaces
; two integers with a '/' between them are interpreted as a fraction
+ ; add the integer part to the fractional part
; implicitly output the fraction


-(----[]]]][]]][{{U]>)D^^D^^^^^R]^}:DON-)}:NE.U[UOUO{^)N+E:]OD-}.U^U[{U^)DPD]P:}


Try It Online! Takes character codes as input and outputs as two numbers Numerator, Denominator.

Explanation:

Fairly straightforward, parses by looping through digits, subtracting 48, and then multiplying by 10 before adding each new number. when it hits a charcode less than 48, it knows to move on to the next number. There's not an easy way to multiply within a single code block to my knowledge, so the next two code blocks respectively copy a bunch of x onto the queue and then add them all up. Probably still golfable within the same approach, I found a few golfs while writing up the explanation, even.

-(----[]]]][]]][{{U]>)D^^D^^^^^R]^}:DON-)}:NE. block 0: parses input
-(                                             r3 = -1
----[]]]][]]][                               r2 = -48
{                     N-)}:    while input remains
{U]>)            }:             while input + r2 > r3
D^^D^^^^^                    r1 *= 10
R]^                 r1 += input + r2
DO           enqueue and reset r1
NE  go to block 1
. end block

U[UOUO{^)N+E:]OD-}. block 1: copies x z times onto queue
U[                  r2 = x
UO                enqueue y
UO              enqueue z
U  ^            r1 = z
{^)   :  D-}  while(r1--){
]O       enqueue x
}
N+E        go to block 2
. end code block

U^U[{U^)DPD]P:} block 2: sums copies of x and adds y, prints x*z+y and z
U^              r1 = y
U[            r2 = z
{U )     :} while items remain unvisited on the queue (all of which are x)
U^           r1 += x
DP      print r1
D]P   print r2