cumulative frequency array in perl?
-
29-06-2021 - |
Question
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!
La solution
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);
}
Autres conseils
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";
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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow