# 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.

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 '15 at 18:31
• Can the output be a rational number type or does it have to be a string? – Martin Ender Dec 17 '15 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 '15 at 18:38
• Can x, y and z be negative? – Dennis Dec 17 '15 at 19:21
• Based on the challenge I'm assuming it is, but is the input format "x y/z" mandatory, or can the space be a new-line, and/or the x,y,z be separated inputs? Most answers are assuming the input format is indeed mandatory to be x y/z, but some aren't, hence this question to have a definitive answer. – Kevin Cruijssen Jun 15 '18 at 13:04

# 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/ – ETHproductions Dec 21 '15 at 22:40

# LabVIEW, 29 LabVIEW Primitives

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

or

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

Test it here.

## Explanation

'/']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. – Esolanging Fruit Jul 13 '17 at 7:15
• An alternate version: '//~\S/1$b'/@, this is 13 bytes. Edit: oh I forgot the input l. – Chromium Jun 15 '18 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! – TessellatingHeckler Dec 18 '15 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. – AdmBorkBork Dec 18 '15 at 13:48
• Oh yeah, just math! (That would be enough to beat a Perl answer, too) – TessellatingHeckler Dec 18 '15 at 14:35

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

Requires import sj224.tflp.math.*;

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) – ETHproductions Dec 18 '15 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 – user81655 Dec 18 '15 at 3:03
• My first crossed out 44! :D – user81655 Dec 18 '15 at 3:04
• You can use m.split(/\W/g) instead to save a byte – Kritixi Lithos Jun 11 '18 at 14:08

# 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. # 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 – H.PWiz Jun 15 '18 at 2:01 • @H.PWiz That is a great use of lex. – Wheat Wizard Jun 15 '18 at 2:03 • 65 bytes: Try it online! – Laikoni Jun 15 '18 at 5:19 • You should be able to save another 2 by matching on the / – H.PWiz Jun 15 '18 at 9:38 • 59 bytes – H.PWiz Jul 9 '18 at 5:17 # 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) – ETHproductions Dec 18 '15 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]". – Dennis Dec 17 '15 at 19:27 • @Dennis I've added that in. Thanks! – ASCIIThenANSI Dec 17 '15 at 19:33 • The #!perl part of the shebang and the linefeed do not count. This is only 38 bytes. – Dennis Dec 17 '15 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) – ASCIIThenANSI Dec 17 '15 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. – SuperJedi224 Dec 17 '15 at 23:49 • @FlagAsSpam But then the variables will be left undeclared! – SuperJedi224 Dec 17 '15 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]); – Addison Crump Dec 17 '15 at 23:55 # 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. – Kevin Cruijssen Jun 15 '18 at 13:05 # 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) – Kevin Cruijssen Jun 15 '18 at 13:02 • 15-bytes – Magic Octopus Urn Jun 15 '18 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! :) – Kevin Cruijssen Jun 15 '18 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. – Magic Octopus Urn Jun 15 '18 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 ''.. – Kevin Cruijssen Jun 15 '18 at 13:18 # 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 '18 at 13:07 # 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. # 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. – Giuseppe Jun 16 '18 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! – Dom Hastings Jun 21 '18 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. – sundar - Reinstate Monica Jun 22 '18 at 13:42

# Lua, 123 Bytes

m=io.read()z=string x=z.find c=z.sub b=tonumber s=x(m," ")f=x(m,"/")d=c(m,f+1)print(b(c(m,1,s))*b(d)+b(c(m,s,f-1)).."/"..d)

# Milky Way 1.6.0, 31 bytes

'" "\="/"\=>;<A;A;:>*;A+"/"+<+!

Ended up being much longer than I thought it would be.

### Explanation

'" "\="/"\=>;<A;A;:>*;A+"/"+<+!

'                                # read input from the command line
" "  "/"               "/"      # push a string to the stack
\    \                       # split the STOS at the TOS
=    =                      # dump the TOS to the stack
>       >             # rotate the stack rightward
;  ; ;   ;           # swap the TOS and STOS
<              <    # rotate the stack leftward
A A     A          # push the integer representation of the TOS
:              # duplicate the TOS
*            # multiply the STOS by the TOS
+   + +   # add the TOS and STOS
!  # output the TOS

### Usage

./mw <path-to-code> -i <input>

## Python 2.7, 88 Bytes

a=input().split('/');print int(a[-1])*int(a[0].split()[0])+int(a[0].split()[1]),'/',a[1]

Try it online!

You have to type the input in quotes.

Probably not the best ...

# C, 64

main(i,d,n){scanf("%d %d/%d",&i,&n,&d);printf("%d/%d",i*d+n,d);}

Reads input from STDIN. Fairly self-explanatory, I think.

## Check, 120 bytes

>]+>:>32r#v
#d@0+\)  ##:>4;:>5'=:>48-\R-?
dd)R>32-#v
#>15-#v  #?
47r@>@   #v
#dd#v #?
r@>@     #v
#\d@\: @*@+pd"/"op

Try it online!

I might be able to save some bytes by not trying to reuse the parsing loop (the second line). That way I could make the loop more specific, avoid the huge mess of conditionals, and I could use the register for other things.

# Ruby, 23 bytes

->x{eval x.split*?++?r}

Try it online!

# C#, 112 bytes

s=>{string[]a=s.Split(),b=a[1].Split('/');int o=int.Parse(b[1]);return int.Parse(a[0])*o+int.Parse(b[0])+"/"+o;}

Full/Formatted Version:

namespace System.Linq
{
class P
{
static void Main()
{
Func<string, string> f = s =>
{
string[] a = s.Split(), b = a[1].Split('/');
int o = int.Parse(b[1]);
return int.Parse(a[0]) * o + int.Parse(b[0]) + "/" + o;
};

Console.WriteLine(f("4 1/2"));
Console.WriteLine(f("12 2/4"));
Console.WriteLine(f("0 0/2"));
Console.WriteLine(f("11 23/44"));

}
}
}

# APL (Dyalog Unicode), 31 bytes

∊∘(⍕¨⊃,⍨'/',⍨⊃⊥1∘↓)¯1⌽#⍎¨∊∘⎕D⊆⊢

Try it online!

Thanks to ngn for the ⊃⊥1∘↓ trick

## PHP, 65 Bytes

Try it online

Code

<?=(($a=preg_split("/[\s,\/]/",$argv))[0]*$a[2]+$a[1])."/".$a[2]; Explanation$a=preg_split("/[\s,\/]/",$argv); # Split the string on "/" and " " (($a)[0]*$a[2]+$a[1]) # as always denominator*whole number + numerator
."/"                  # echo an slash
.\$a[2];               # echo de denominator

# Java 10, 87 bytes

A lambda from String to String.

s->{var p=s.split(" |/");return new Long(p[0])*new Long(p[2])+new Long(p[1])+"/"+p[2];}

Try It Online