Skip to content

Instantly share code, notes, and snippets.

@tsee
Created July 17, 2011 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsee/1087863 to your computer and use it in GitHub Desktop.
Save tsee/1087863 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
my @data = (
{end => 1000, duration => 100, records => 100},
{end => 1600, duration => 300, records => 400},
{end => 1200, duration => 150, records => 50},
{end => 1300, duration => 500, records => 900},
);
my $time_start = 500;
my $time_end = 2500;
my $xy = make_plot(\@data, $time_start, $time_end);
use Data::Dumper;
warn Dumper $xy;
sub make_plot {
my $data = shift();
my $start_time = shift;
my $end_time = shift;
my @jumps;
foreach my $datum (@$data) {
my $rec_per_time = $datum->{records} / ($datum->{duration} || 1);
my $end = $datum->{end};
my $start = $end - $datum->{duration};
$start-- if $start == $end; # for 0-time periods...
push @jumps, {when => $start, diff => $rec_per_time},
{when => $end, diff => -$rec_per_time};
}
@jumps = sort { $a->{when} <=> $b->{when} } @jumps;
my $y = 0;
while (@jumps && $jumps[0]->{when} < $start_time) {
$y += shift(@jumps)->{diff}; # here's the non-OO hacky variant just for you >:)
}
# start collecting points for plotting
my @plot_coords; # to contain arrayrefs of [$x, $y]
push @plot_coords, [$start_time, $y]; # start point
while (@jumps) {
my $j = shift @jumps;
last if $j->{when} > $end_time;
push @plot_coords, [$j->{when}, $y];
$y += $j->{diff};
push @plot_coords, [$j->{when}, $y];
}
push @plot_coords, [$end_time, $y];
return \@plot_coords;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment