an alternate pm pm =: 1 : '(% +./)@((u/@:* |.) , */@])"1'
________________________________ From: Louis de Forcrand <[email protected]> To: [email protected] Sent: Sunday, March 6, 2016 12:31 PM Subject: [Jprogramming] Fractions challenge Try to write a verb or adverb(s) that can add, subtract, multiply, and divide two vectors of shape two which represent two exact fractions: 1 2 plus 3 4 5 4 1 2 minus 3 4 _1 4 1 2 times 3 4 3 8 1 2 divide 3 4 2 3 At first sight this may seem useless, as exact arithmetic is already implemented, but the idea is to have your function work with complex numbers as well: 0j1 1j2 plus 0j1 2j1 _3j3 0j5 0j1 1j2 minus 0j1 2j1 1j1 0j5 0j1 1j2 times 0j1 2j1 _1 0j5 0j1 1j2 divide 0j1 2j1 9.0072e15 7.20576e15j5.40432e15 NB. “exact” ; if you ask J to do the division, the result is correctly rounded off. 2 x: 2.5 3 3.5 ,: 4 4.5j2.5 5 |domain error | 2 x:2.5 3 3.5,:4 4.5j2.5 5 frc 2.5 3 3.5 ,: 4 4.5j2.5 5 NB. convert to fractions 5 2 3 1 7 2 4 1 7j_2 1j_1 5 1 The fractions need to be simplified (so the numerator and denominator are relatively prime), so I would suggest first finding how to simplify them (that shouldn’t be too hard). If you feel like it, you can write two other verbs to convert between fraction vector and decimal representation as well. Mine (two adverbs and two verbs; +/- and */%, plus conversion & simplification): pm=: 1 : '(% +./)@(*&{: ,~ ,&{. u/@:* ,~&{:)"1' NB. Plus Minus -> m +pm n td=: 1 : '(% +./)@:u"1’ NB. Times Divide -> m *td n simp=: (% +./)"1 NB. SIMPlify fractions dec=: %/"1 :.((* (% +./)@,"0 ]) (>:@- >.)) NB. convert to DECimal/fraction PS: On http://www.jsoftware.com/mailman/listinfo/programming <http://www.jsoftware.com/mailman/listinfo/programming> it says to send messages to [email protected] <mailto:[email protected]>. Shouldn’t this be simply [email protected] <mailto:[email protected]>? Good luck, Louis ---------------------------------------------------------------------- For information about J forums see http://www.jsoftware.com/forums.htm ---------------------------------------------------------------------- For information about J forums see http://www.jsoftware.com/forums.htm
