Code Golf Asked by user65167 on January 13, 2021

Write a program or a function that takes two non-empty lists of the same length as input and does the following:

- uses elements of first list to get numerators,
- uses elements of the second list to get denominators,
- displays resulting fractions after simplification
`(2/4=>1/2)`

, separated by “+”s, - displays “=” and result of addition after last fraction.

```
[1, 2, 3, 3, 6]
[2, 9, 3, 2, 4]
```

```
1/2+2/9+1+3/2+3/2=85/18
```

- elements of lists will be positive integers,
- elements can be separated by spaces, eg:
`1/2 + 2/9 + 1 + 3/2 + 3/2 = 85/18`

is ok, - trailing newline is allowed,
- lists can be taken in other formats than above, eg.:
`(1 2 3 3 6)`

or`{1;2;3;3;6}`

, etc., `1`

can be expressed as`1/1`

,- instead of printing you can return appropriate string,
- you do not need to handle wrong input,
**shortest code wins**.

```
÷µFj”+;”=;S
```

This is a dyadic link. Due to a bug, it doesn't work as a full program. `F`

is also required due to a bug.

```
÷µFj”+;”=;S Dyadic link. Left argument: N. Right argument: D
÷ Perform vectorized division, yielding an array of fractions (R).
µ Begin a new, monadic chain. Argument: R
F Flatten R. R is already flat, but j is buggy and has side effects.
j”+ Join R, separating by '+'.
;”= Append '='.
;S Append the sum of R.
```

Correct answer by Dennis on January 13, 2021

```
=ArrayFormula(JOIN("+",TRIM(TEXT(A:A/B:B,"?/???")))&"="&TEXT(sum(A:A/B:B),"?/???"
```

_{Saved 2 bytes thanks to Taylor Scott}

Sheets will automatically add 2 closing parentheses to the end of the formula.

The two arrays are input as the *entirety* of columns `A`

and `B`

. Empty rows below the inputs will throws errors.

Answered by Engineer Toast on January 13, 2021

```
t=tail.(([n,_,d]->'+':n++'/':d).words.show=<<)
a#b|f<-zipWith(%)a b=t f++'=':t[sum f]
```

Thanks @Laikoni for `-8`

bytes!

```
-- convert each fraction to a string (has format "n%d", replace '%' with '/' and prepend '+' ("+n/d"), keep the tail (dropping the leading '+')
t = tail.(([n,_,d]->'+':n++'/':d).words.show=<<)
-- build a list of fractions
a # b = let f = zipWith(%) a b in
-- stringify that list, append "=" and the stringified sum of these fractions
t f ++ "=" ++ t [sum f]
```

Answered by ბიმო on January 13, 2021

```
Dim(List 1)->A
for 1->I to A step 1
3*I-2->B
List 1[I]->C
List 2[I]->D
locate 1,B,C
locate 1,B+1,"/"
locate 1,B+2,D
C/D+E->E
next
locate 1,B+3,"="
locate 1,B+4,E
```

Explanation:

- Number of input is saved in
`A`

`A`

iterations`B`

acts as a counter for correct displaying`I`

'th item of List 1 and 2 saved in`C`

and`D`

- Displaying of Variable
`C`

/ Variable`D`

- save
`C`

/`D`

+`E`

in`E`

- After last number locate
`=`

and`E`

Answered by ADDB on January 13, 2021

```
C==>concat;S==>String;g(a)==C[numerator(a)::S,"/",denom(a)::S];h(a:List PI,b:List PI):S==(r:="";s:=0/1;#a~=#b or #a=0=>"-1";for i in 1..#a repeat(v:=a.i/b.i;s:=s+v;r:=C[r,g(v),if i=#a then C("=",g(s))else"+"]);r)
```

test

```
(5) -> h([1,3,4,4,5,6], [2,9,5,5,6,7])
(5) "1/2+1/3+4/5+4/5+5/6+6/7=433/105"
Type: String
(6) -> h([1,3,4,4], [2,9,5,5,6,7])
(6) "-1"
Type: String
```

Answered by user58988 on January 13, 2021

```
[a,b]|->join([x/y:[x,y]in a><b],"+")+"="++/[x/y:[x,y]in a><b];
```

```
[a,b]|-> define a function with parameters a and b
join(
[ x/y : using set comprehension, make a list of fractions
[x,y] in a><b from the lists zipped together
],
"+"
) join them with "+"
+ "=" concat with an equals sign
+ concat with
+/[x/y:[x,y]in a><b] the sum of the list
;
```

Answered by corvus_192 on January 13, 2021

```
f:=procedure(a,b){i:=1;l:=[];while(i<=#a){l:=l+[a[i]/b[i]];i+=1;}s:=join(l,"+");return s+"="+eval(s);};
```

Creates a function called `f`

where your insert two lists.

ungolfed:

```
f := procedure (a,b) {
i:=1;
l:=[];
while(i<=#a){
l:=l+[a[i]/b[i]];
i+=1;
}
s:=join(l,"+");
return s+"="+eval(s);
};
```

with named variables and annotations:

_{setlX doesn't provide a comment feature so let's just pretend that we can comment with %}

```
f := procedure(firstList,secondList) {
count := 1;
list := [];
while(count <= #firstList) {
% calculate every fraction and save it as a list
list := list + [firstList[count]/secondList[count]];
count += 1;
}
% Seperate every list entry with a plus ([2/3,1] -> "2/3+1")
str := join(list, "+");
% eval executes the string above and thus calculates our sum
return str + "=" + eval(str);
};
```

Answered by BlueWizard on January 13, 2021

```
i;t;x;y;f(int s,int*a,int*b){x=*a;y=*b;while(++i<s)x=(y-b[i])?(x*b[i])+(a[i]*y):(x+a[i]),y=(y-b[i])?(b[i]*y):y;for(i=1;i<=(x<y?x:y);++i)t=(x%i==0&&y%i==00)?i:t;x/=t;y/=t;}
```

Answered by Khaled.K on January 13, 2021

```
<?function f($x,$y){for($t=1+$x;$y%--$t||$x%$t;);return$x/$t."/".$y/$t;}[$n,$d]=$_GET;for($p=array_product($d);$x=$n[+$k];$e+=$x*$p/$y)$r[]=f($x,$y=$d[+$k++]);echo join("+",$r)."=".f($e,$p);
```

+14 Bytes for replacement `return$x/$t."/".$y/$t;`

with `return$y/$t>1?$x/$t."/".$y/$t:$x/$t;`

to output `n`

instead of `n/1`

Answered by Jörg Hülsermann on January 13, 2021

```
let rec g a=function|0->abs a|b->g b (a%b)
let h a b=g a b|>fun x->a/x,b/x
let s,n,d=List.fold2(fun(s,n,d)N D->
let(N,D),(n,d)=h N D,h(n*D+N*d)(d*D)
[email protected][sprintf"%i/%i"N D],n,d)([],0,1)nom div
printf"%s=%i/%i"(System.String.Join("+",s))n d
```

Answered by Brunner on January 13, 2021

```
:L₁⁄L₂ //Creates a fraction from Lists 1 & 2, 7 bytes
:toString(Ans→Str1 //Create string from list, 7 bytes
:inString(Ans,",→A //Look for commas, 9 bytes
:While A //Begin while loop, 3 bytes
:Str1 //Store Str1 to Ans, 3 bytes
:sub(Ans,1,A-1)+"+"+sub(Ans,A+1,length(Ans)-A→Str1 //Replace "," with "+", 33 bytes
:inString(Ans,",→A //Check for more commas, 9 bytes
:End //End while loop, 2 bytes
:Str1 //Store Str1 to Ans, 3 bytes
:sub(Ans,2,length(Ans)-2 //Remove opening and closing brackets, 13 bytes
:Ans+"="+toString(expr(Ans //Add "=" and answer, 11 bytes
```

Note the `⁄`

at the beginning, different from `/`

. This makes the fractions hold their forms. It **does** work with negative fractions.

*Sigh*. TI-BASIC is *horrible* with strings. If all we had to do was print the fractions, and then their sum, the code would be:

```
:L₁⁄L₂ //Create fractions from lists, 7 bytes
:Disp Ans //Display the above fractions, 3 bytes
:sum(Ans //Display the answer, 2 bytes
```

That means that **88 bytes** of my code is spent just formatting the answer! *Hmph*.

Answered by Scott Milner on January 13, 2021

*-13 bytes thanks to Dennis*

```
a^b=replace(join(a.//b,"+")"=$(sum(a.//b))","//","/")
```

Alternately, if fractions can be displayed using `//`

rather than `/`

, the following works for **35 bytes**:

```
a^b=join(a.//b,'+')"=$(sum(a.//b))"
```

Answered by Julian Wolf on January 13, 2021

```
f=MASS::fractions;a=attributes
g=function(n,d)paste(paste(a(f(n/d))$f,collapse='+'),a(f(sum(n/d)))$f,sep='=')
```

requires the `MASS`

library (for its `fractions`

class). the function `g`

returns the required output as a string.

Try it online! (R-fiddle link)

Answered by Giuseppe on January 13, 2021

Answered by Leaky Nun on January 13, 2021

```
/YQv'%i/%i+'wYD3L)61yUYQVwV47b&h
```

Try at MATL online!

Consider `[1, 2, 3, 3, 6]`

, `[2, 9, 3, 2, 4]`

as input.

```
/ % Implicit inout. Divide element-wise
% STACK: [0.5 0.222 1 1.5 1.5]
YQ % Rational approximation (with default tolerance)
% STACK: [1 2 1 3 3], [2 9 1 2 2]
v % Conctenate all stack elements vertically
% STACK: [1 2; 2 9; 1 2; 3 2; 3 2]
'%i/%i+' % Push this string (sprintf format specifier)
% STACK: [1 2; 2 9; 1 2; 3 2; 3 2], '%i/%i+'
wYD % Swap, sprintf
% STACK: '1/2+2/9+1/1+3/2+3/2+'
3L) % Remove last entry
% STACK: '1/2+2/9+1/1+3/2+3/2'
61 % Push 61 (ASCII for '=')
% STACK: '1/2+2/9+1/1+3/2+3/2', 61
y % Duplicate from below
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, '1/2+2/9+1/1+3/2+3/2'
U % Evaluste string into a number
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, 4.722
YQ % Rational approximation
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, 85, 18
VwV % Convert to string, swap, convert to string
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, '18', '85'
47 % Push 47 (ASCII for '/')
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, '18', '85', 47
b % Bubble up in stack
% STACK: '1/2+2/9+1/1+3/2+3/2', 61, '85', 47, '18'
&h % Concatenate all stack elements horizontally. Implicitly display
% STACK: '1/2+2/9+1/1+3/2+3/2=85/18'
```

Answered by Luis Mendo on January 13, 2021

```
#(let[S(map / % %2)](apply str(concat(interpose '+ S)['=(apply + S)])))
```

Yay for built-in fractions!

Answered by NikoNyrh on January 13, 2021

```
int c(int a,int b){return b>0?c(b,a%b):a;}
(N,D)->{int n=0,d=1,i=0,g;String s="";for(;i<N.length;g=g(N[i],D[i]),N[i]/=g,D[i]/=g,s+=(i>0?"+":"")+N[i]+"/"+D[i],n=n*D[i]+N[i]*d,d*=D[i++],g=g(n,d),n/=g,d/=g);return s+"="+n+"/"+d;}
```

`N`

and `D`

are both `int[]`

, contextualized.

I reused Kevin Cruijssen's GCD function.

Answered by Olivier Grégoire on January 13, 2021

```
{join('+',($/=[@^a Z/ @^b]).map:{.nude.join('/')})~"="~$/.sum.nude.join('/')}
```

```
{($/=[@^a Z/@^b])».nude».join('/').join('+')~'='~$/.sum.nude.join('/')}
```

```
{ # bare block lambda with two placeholder params ｢@a｣ and ｢@b｣
(
$/ = [ # store as an array in ｢$/｣ for later use
@^a Z/ @^b # zip divide the two inputs (declares them)
]
)».nude # get list of NUmerators and DEnominators
».join('/') # join the numerators and denominators with ｢/｣
.join('+') # join that list with ｢+｣
~
'=' # concat with ｢=｣
~
$/.sum.nude.join('/') # get the result and represent as fraction
}
```

Answered by Brad Gilbert b2gills on January 13, 2021

Native and automatic rationals *should* make this easy, but default stringification is still as decimal, so we have to `.nude`

(*nu*merator and *de*nominator) which kills our score and makes the 1 ugly :(

```
my n = 1,2,3,3,6; my d = 2,9,3,2,4;
(n Z/d)».nude».join("/").join("+")~"="~([+] n Z/d).nude.join("/")
```

Update: Removed unneeded brackets, kill more space and use smarter map. Saves characters over Brad's solution at the cost of no not being a lambda sub.

Answered by Dean Serenevy on January 13, 2021

```
[email protected]{Row[#/#2,"+"],"=",Tr[#/#2]}&
```

input

[{1, 2, 3, 3, 6}, {2, 9, 3, 2, 4}]

Answered by J42161217 on January 13, 2021

Takes the lists in currying syntax `(a)(b)`

.

```
let f =
a=>b=>a.map((v,i)=>F(A=v,B=b[i],N=N*B+v*D,D*=B),N=0,D=1,F=(a,b)=>b?F(b,a%b):A/a+'/'+B/a).join`+`+'='+F(A=N,B=D)
console.log(f([1, 2, 3, 3, 6])([2, 9, 3, 2, 4]))
```

Answered by Arnauld on January 13, 2021

```
->n,d{a=n.zip(d).map{|n,d|n.to_r/d};a*?++"=#{a.sum}"}
```

Thanks to:

- Value Ink for the Ruby 2.4 specific version (-3 characters)
- Value Ink for optimizing the
`Rational`

initialization (-1 character)

```
->n,d{t=0;n.zip(d).map{|n,d|t+=r=n.to_r/d;r}*?++"=#{t}"}
```

Sample run:

```
irb(main):001:0> puts ->n,d{t=0;n.zip(d).map{|n,d|t+=r=n.to_r/d;r}*?++"=#{t}"}[[1, 2, 3, 3, 6], [2, 9, 3, 2, 4]]
1/2+2/9+1/1+3/2+3/2=85/18
```

Answered by manatwork on January 13, 2021

```
t=#~ToString~InputForm&;Riffle[t/@#,"+"]<>"="<>[email protected]@#&[#/#2]&
```

Answered by alephalpha on January 13, 2021

Answered by Emigna on January 13, 2021

9 bytes thanks to Felipe Nardi Batista.

```
from fractions import*
def f(*t):c=[Fraction(*t)for t in zip(*t)];print('+'.join(map(str,c)),'=',sum(c))
```

Answered by Leaky Nun on January 13, 2021

6 Asked on January 4, 2022 by katenkyo

11 Asked on December 24, 2021 by adm

5 Asked on December 24, 2021

20 Asked on December 24, 2021

2 Asked on December 21, 2021 by darrylyeo

358 Asked on December 10, 2021

20 Asked on December 10, 2021 by kevin-cruijssen

2 Asked on November 30, 2021

61 Asked on November 28, 2021

Get help from others!

Recent Questions

- How Do I Get The Ifruit App Off Of Gta 5 / Grand Theft Auto 5
- Iv’e designed a space elevator using a series of lasers. do you know anybody i could submit the designs too that could manufacture the concept and put it to use
- Need help finding a book. Female OP protagonist, magic
- Why is the WWF pending games (“Your turn”) area replaced w/ a column of “Bonus & Reward”gift boxes?
- Does Google Analytics track 404 page responses as valid page views?

Recent Answers

- Lex on Does Google Analytics track 404 page responses as valid page views?
- Jon Church on Why fry rice before boiling?
- Peter Machado on Why fry rice before boiling?
- haakon.io on Why fry rice before boiling?
- Joshua Engel on Why fry rice before boiling?

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir