Hey Jon, It can be written in one go, try:
+/@result f. This fixes the all verbs, converting a verb to it's constituent primitives. That said, you are over-specifying your ranks. Ranks are there by default, and as it happens = already has rank 0, so there is no use in setting the ranks. Other things to note are : you can use a for for dummy, and instead of multiplying with 1, it's easier to use the identity function (which, as a bonus works also for non-numeric types). Now a fork as ( ] f g ) is equivalent to the hook (f g). A last simplification is that the left most tine of a fork ( A in the fork (A B C) can be a constant, in which case it is interpretted as a verb returning the constant as result. You can also use | with different left and right ranks, so as to take one of the left side, and the entire row at the right by using (|" 0 1). Like this you can combine the div3 and div5. All combined, I would write it as: +/ @ (#~ +./@ ( 0=5 3 |"0 1]) ) i. 1000 Here, the fork ( 0=5 3 |"0 1]) returns the whether the number is divisible by 5 or 3, in rows, +./@ combines them, and #~ selects those items from the original array (note it is part of a hook). The +/@ finally sums all qualifying elements. Probably there are people better in explaining than me ... Jan-Pieter 2014-04-08 17:30 GMT+02:00 Jon Hough <[email protected]>: > Euler Project #1 is:If we list all the natural numbers below 10 that are > multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is > 23. Find the sum of all the multiples of 3 or 5 below 1000. > In C/Java I could easily do something like: > int total =0; > for (int counter = 0; counter < 1000; counter ++ ){if(counter %3 = 0 || > counter %5 = 0){ total += counter;}} > return counter; > > The main features here being the if statement and the for-loop. > Obviously in J things need to be done differently. Here is my first > attempt: > div3 =. 0&(="0)@:( 3&|) NB. is residue zerodiv5 =. 0&(="0)@:( 5&|) > div3or5 =. div3"0 +."0 div5"0 > dummy =. 1&*"0 NB. You'll see why I need this... > result =. dummy * div3or5 > NB. final result is: > +/result i.1000 > > I used dummy because I wanted to do something like multiply the value of > y by "div3or5 y" so only multiples of 3 or 5 would be nonzero. > Before attempting this problem I assumed it could be done in only one line > and am pretty unhappy by my long solution. Any help explaining where I have > gone wrong, or why my attempt at a fork is silly would be appreciated. > Thanks in advance, > Jon > > > ---------------------------------------------------------------------- > For information about J forums see http://www.jsoftware.com/forums.htm > ---------------------------------------------------------------------- For information about J forums see http://www.jsoftware.com/forums.htm
