ran1n
ran1n

Reputation: 157

sort and manipulation of hash with average calculations

I am having a hash whose keys are time instances and values are process time taken in milliseconds. I am working on a solution wherein user will input a time value and in return should get average of all process times before the inputted time.

Example: if user enters 07:47:42, he should get average of process times of keys 04:46:41, 03:46:37, 06:47:41, 00:45:35, 01:46:05.

Please suggest how to do this. Do i need to convert the strings in time or can it be done in strings only. Any code samples would be really helpful. Thanks!

$VAR1 = {
          '01:46:05' => '119.947ms',
          '11:47:47' => '165.916ms',
          '15:48:51' => '164.226ms',
          '19:50:22' => '159.873ms',
          '10:47:45' => '177.947ms',
          '04:46:41' => '174.613ms',
          '16:49:22' => '169.104ms',
          '00:45:35' => '122.289ms',
          '18:49:52' => '158.956ms',
          '06:47:41' => '145.969ms',
          '09:47:44' => '85.786ms',
          '12:48:16' => '132.169ms',
          '05:47:11' => '186.575ms',
          '03:46:37' => '131.529ms',
          '07:47:42' => '121.417ms',
          '21:50:55' => '171.268ms',
        };

Upvotes: 0

Views: 70

Answers (1)

ikegami
ikegami

Reputation: 385915

sub sum { my $acc; $acc += $_ for @_; $acc }
sub avg { sum(@_) / @_ }

my $cutoff = '07:47:42';

my $result =
   avg
      map { substr($VAR1->{$_}, 0, -2) }
         grep { $_ lt $cutoff }
            keys %$VAR1;

Upvotes: 2

Related Questions