0

I've got an array of integers and i was wondering how you would code for a cumulative frequency array. should i use a for loop or is there a quicker way.

e.g given integers: 1 2 3 4 5 6 7 8 the new array would print: 1 3 6 10 15 21 28 36 thanks!

user1637359
  • 227
  • 4
  • 10

3 Answers3

0

You could also use map instead of foreach ... push:

#!/usr/bin/perl -w
use strict;
my @arr = 1..10;
my $sum;
my @newarr = map { $sum += $_ } @arr;
print "@newarr\n";
Dallaylaen
  • 5,268
  • 20
  • 34
0

This is very easily done in a single for loop

use strict;
use warnings;

my @data = 1 .. 8;

my @cumulative = $data[0];
push @cumulative, $cumulative[-1] + $_ for @data[1..$#data];

print "@cumulative\n";

output

1 3 6 10 15 21 28 36
Borodin
  • 126,100
  • 9
  • 70
  • 144
-1

one way, very inefficient:

    #!/usr/bin/env perl
    use strict;
    use warnings;
    use List::Util qw/sum/;

    my @arr = (1..10);
    my @newarr;

for my $i (0..$#arr) {
    $newarr[$i] = sum(@arr[0..$i]) 
}

looping and summing is much better:

use strict;
use warnings;

my @arr = (1..10);
my @newarr;
my $mid;

for my $i (0..$#arr) {
  $mid += $arr[$i];
  push(@newarr,$mid);
}
snoofkin
  • 8,725
  • 14
  • 49
  • 86