Compressing multiple columns into one

Compressing multiple columns into one

am 19.06.2008 17:05:07 von Jean-Rene David

Hi,

A little problem I encountered recently.

I have an array of integers and two indexes within
that array. I need to get another array identical
to the first one, except that all cells between
the two indexes (inclusive) must be compressed to
one column which is the sum of the originals
cells.

A program will illustrate below.

What I'm looking for is just a way to do the same
thing more elegantly. It has nested loops using
the same index variable and a duplicated test,
which are both a little ugly.

#!/usr/bin/perl

use warnings;
use strict;

my @array = qw{ 10 20 30 40 50 };
my $start = 1;
my $end = 3;

my @out;
for( my $i = 0; $i < @array; $i++) {
my $j;
for( ; $i >= $start && $i <= $end; $i++) {
$j += $array[$i];
if( $i == $end ) {
push @out, $j;
}
}
push @out, $array[$i];
}

$\="\n";
print for @out;

The expected out is:
10
90
50

The second line contains the sum of elements 1, 2
and 3.

Thanks for any input,

--
JR

--
To unsubscribe, e-mail: beginners-unsubscribe@perl.org
For additional commands, e-mail: beginners-help@perl.org
http://learn.perl.org/

Re: Compressing multiple columns into one

am 20.06.2008 07:26:30 von emenzhaowork

------=_Part_655_17994113.1213939590714
Content-Type: text/plain; charset=ISO-8859-1
Content-Transfer-Encoding: 7bit
Content-Disposition: inline

Hello,
How about this?

my @test = qw(10 20 30 40 50);
splice @test, 1, 3, $test[1]+$test[2]+$test[3];
print "@test";

Thanks,
--Emen

On Thu, Jun 19, 2008 at 4:05 PM, Jean-Rene David wrote:

> Hi,
>
> A little problem I encountered recently.
>
> I have an array of integers and two indexes within
> that array. I need to get another array identical
> to the first one, except that all cells between
> the two indexes (inclusive) must be compressed to
> one column which is the sum of the originals
> cells.
>
> A program will illustrate below.
>
> What I'm looking for is just a way to do the same
> thing more elegantly. It has nested loops using
> the same index variable and a duplicated test,
> which are both a little ugly.
>
> #!/usr/bin/perl
>
> use warnings;
> use strict;
>
> my @array = qw{ 10 20 30 40 50 };
> my $start = 1;
> my $end = 3;
>
> my @out;
> for( my $i = 0; $i < @array; $i++) {
> my $j;
> for( ; $i >= $start && $i <= $end; $i++) {
> $j += $array[$i];
> if( $i == $end ) {
> push @out, $j;
> }
> }
> push @out, $array[$i];
> }
>
> $\="\n";
> print for @out;
>
> The expected out is:
> 10
> 90
> 50
>
> The second line contains the sum of elements 1, 2
> and 3.
>
> Thanks for any input,
>
> --
> JR
>
> --
> To unsubscribe, e-mail: beginners-unsubscribe@perl.org
> For additional commands, e-mail: beginners-help@perl.org
> http://learn.perl.org/
>
>
>

------=_Part_655_17994113.1213939590714--