Hi Ian -

J has a handy adverb called "table" which is the forward slash "/".  This
allows you to apply a function orthogonally, e.g.
    1 2 3 4 5 +/ 1 2
adds each number on the left to each on the right, giving you a 5 by 2
table.  Once you have this, it's simple to
sum the ravel of the result, i.e.
   +/,1 2 3 4 5 +/ 1 2

If you want to analyze this algorithm more, perhaps you'll come up with a
very different way to do it once you notice that each element of the
left-had side is being added (number of right-hand side) times and
conversely for the right-hand side.

Regards,

Devon

On 8/3/08, Ian Gorse <[EMAIL PROTECTED]> wrote:
>
> Hi,
>
> I know several programming languages, but I am still new to J, and the
> whole
> style of programming is alot different to what I am used too, but I am
> finding it extremely interesting, as it makes me think of ways to solve
> problems differently to what I normally do.
>
> I keep running into the same problem over and over again (probably because
> I
> have spent so long with 'standard' programming languages), and that is
> writing a script that doesn't use explicit loops.
>
> Even though I have solved the problem I was trying to solve in J, I would
> like to do it without using a loop like I did.
>
> I have simplified my problem to try and explain what I am trying to do.
>
> a=. 1 2 3 4 5
> b=. 1 2
>
> I want to be able to add each of the values in 'b' with each of the values
> in 'a', then sum them up
>
>
> for example
> (a[0]+b[0])  + (a[1]+b[0])  + (a[2]+b[0])  +(a[3]+b[0])  + (a[4]+b[0]) ) =
> 2
> 3 4 5 6 = 20
> which is (1+1) +  (2+1) +  (3+1) + (4+1) + (5+1) = 20
>
> (a[0]+b[1])  + (a[1]+b[1])  + (a[2]+b[1])  +(a[3]+b[1])  + (a[4]+b[1]) ) =
> 3
> 4 5 6 7 = 25
> which is (1+2) +  (2+2) +  (3+2) + (4+2) + (5+2) = 25
>
> total = 20 + 25 = 45
>
>
> The way I solved it was with
>
>    loop =. 4 : 0
> counter=.0
> sum=.0
> while. counter < #y
> do. sum=. sum + (+/ ((counter { y) + x))
> counter=.counter+1
> end.
> sum
> )
>
>   a loop b
>
> but I don't like this method, and would like to find a more direct approach
> without using the program control flow
> ----------------------------------------------------------------------
> For information about J forums see http://www.jsoftware.com/forums.htm
>



-- 
Devon McCormick, CFA
^me^ at acm.
org is my
preferred e-mail
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to