Kairit -
as a rule, in J, you should be suspicious of any loop and ask the question:
am I doing something here that is intrinsically serial?
In the example above, it seems evident to me the answer is no. Then again,
I've been doing this sort of thing for longer than the lifetime of the
average beagle, so YMMV.
To summarize what the first loop accomplishes: keep subtracting successive
elements of the row (from a random number) until we get to or below zero.
So, to turn this around and state more simply: where is the cumulative sum
of the row greater than some arbitrary value? That is,
index=. (roll>+/\row) i. 0
gives the same index calculated by the loop.
The latter part of this code, we want to make the index one if it's zero but
leave it alone otherwise, or
index=. 1>.index NB. Whichever is greater, one or the existing value
(since we know index >:0)
So, the two loops become the simple expression
1>.0 i.~roll>+/\row
and "roll" is calculated from "row" but used only once so there's no point
assigning it a name, so this becomes
1>.0i.~(?+/row)>+/\row
Presumably you want to do this to all the rows. One way to do this is to
fashion the statement above into a function
rowWork=: 13 : '1>.0 i.~(?+/y)>+/\y'
then apply this to each row of y:
rowWork"1 y
Hope you find this helpful.
On 1/18/08, Kairit Sirts <[EMAIL PROTECTED]> wrote:
>
> >
> > In fact, I think it would be a fruitful discussion to compare and
> contrast
> > the cases where we use:
> >
> > * "
> > * /
> > * ^:iteration_calculator
> > * ^:condition^:_
> > * $:
> > * for. and while.
> >
> > I say that because I struggled with the third sentence of this
> message. I
> > couldn't quite articulate the type of problem which would cause one to
> use
> > $: instead of ^: .
> >
> > -Dan
>
> I myself am far too incompetent to start this fruitful discussion, but
> actually I do have several peaces of code which are implemented with for
> or
> while loops. I don't like them and I'm quite sure there are nicer ways to
> write them, but it has been to complicated to me so far.
>
> For example the following peace:
>
> y is a matrix of shape n * n
> x is a number between 0..n-1
>
> roll =. ?+/ row =. x { y
> index =. 0
> while. roll > 0 do.
> roll. =. roll. - index { row
> index =: >: index
> end.
> if. index = 0 do.
> index =. 1
> end.
>
> For the last if-clause I figured out something like this:
>
> check =: =&0^:(=&0)
>
> And 'check index' seems to work as expected, but I'm not quite sure if it
> really is working correctly
>
> Kairit Sirts
>
>
> ----------------------------------------------------------------------
> 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