Sherlock, Ric wrote:
>
> Was solving a recent Rosetta Code task
> http://rosettacode.org/wiki/Equilibrium_index
>
> "An equilibrium index of a sequence is an index into the sequence such
> that the sum of elements at lower indices is equal to the sum of elements
> at higher indices."
>
> My first idea was the most obvious:
> eq0=: +/\ I.@:= +/\.
>
> The idea of calculating the running sums twice seemed non-optimal so I
> came up with the following:
> eq1=: I.@(= (+/ - 2 * +/\ - ]))
> eq2=: I.@(+/ = +:@(+/\) - ])
> eq3=: I.@(+/ = (2 * +/\) - ])
>
> I was pretty happy with that, but then decided to test how much better it
> was.
>
> ts=: 6!:2 , 7!:2...@]
> seq=: _25 + 1e6 ?...@$ 50
>
> 10 ts 'eq0 tst'
> 0.0133672715 8913728
> 10 ts 'eq1 tst'
> 0.0283096334 8389504
> 10 ts 'eq2 tst'
> 0.0228435712 8389440
> 10 ts 'eq3 tst'
> 0.0217780194 8389440
>
> Very nice to see that the simplest, most intuitive answer is also the
> fastest. Thanks Roger/Ken!
>
>
Some improvement (about 10% in speed) of eq1,2,3
is possible if we notice:
f/ === {:@(f/\) === {.@(f/\.)
so there is no need to compute the sum after computing the partial sum,
and we get:
eq2a =: I.@({:@] = +:@] - [) +/\
--
View this message in context:
http://old.nabble.com/Equilibrium-index-tp29793054s24193p29806840.html
Sent from the J Programming mailing list archive at Nabble.com.
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm