in reply to Adding a lot of small integers

On my C2D 2GHz your code is executed in 4.4s with 5.10.1 and in 4.0s with 5.8.9. The following code takes about 3.7s:

@f = <>; for (1..shift(@f)) { @s=(); for (1 .. shift(@f)) { @l = split ' ', shift @f; $i=0; $y=0; for (@l) { $x = $y; $y = $s[$i++]; $_ += $x > $y ? $x : $y; } @s = @l; } $m = 0; $m = $m > $_ ? $m : $_ for @s; print "$m\n"; }

And this seems slightly faster:

for ( 1 .. <> ) { @s = (); for ( 1 .. <> ) { @l = split ' ', <>; ( $i, $y ) = ( 0, 0 ); for (@l) { $x = $y; $y = $s[$i]; $s[ $i++ ] = $x > $y ? $_ + $x : $_ + $y; } } $m = 0; $m = $m > $_ ? $m : $_ for @s; print "$m\n"; }

Replies are listed 'Best First'.
Re^2: Adding a lot of small integers
by kappa (Chaplain) on Jan 10, 2010 at 01:07 UTC

    Thanks, I like this top-down approach! Somehow, it didn't come to me in the first place.

    Btw, I managed to squeeze some more time from your second variant by replacing @s = () with @s = (0) x 100. Benefit from pre-allocating memory for all elements, I suppose.

    --kap