This repository has been archived by the owner on Oct 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Average.pm
85 lines (66 loc) · 1.96 KB
/
Average.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package DDG::Goodie::Average;
# ABSTRACT: take statistics for a list of numbers
use strict;
use DDG::Goodie;
triggers startend => "avg", "average", "mean", "median", "root mean square", "rms";
zci is_cached => 1;
zci answer_type => "average";
handle remainder => sub {
my $query = $req->query_lc;
my $type;
if ($query =~ m/root mean square|rms/) {
$type = "Root Mean Square";
} elsif ($query =~ m/avg|average|mean/) {
$type = "Mean";
} else {
$type = "Median";
}
#Remove leading/trailing text from list of numbers
s/^[a-zA-Z\s]+//;
s/\s+[a-zA-Z]+$//;
#Ensure numbers are space-delimited
s/[;,\s{}\[\]\(\)]+/ /g;
#Return unless only left with space-delimited list of numbers
return unless /^\s*(?:\d+(?:\.\d+)?\s?)*$/;
#Get numbers into an array
my @nums = split ' ', $_;
#Must have at least two numbers
return unless @nums > 1;
# initialize the sum
my $sum;
# calculate the sum
$sum += $_ for @nums;
# get the length of the array
my $len = @nums;
my $result;
if ($type eq "Mean") {
# calculate the mean
$result = $sum/$len;
} elsif ($type eq "Median") {
# sort the list numerically, least to greatest
@nums = sort { $a <=> $b } @nums;
if ($len % 2 eq 0) {
# get the two middle numbers, since the
# length is even, and calculate their mean
$result = ($nums[$len/2] + $nums[$len/2-1])/2;
} else {
# get the middle number
$result = $nums[int($len/2)]
}
} else {
$result += ($_ ** 2) for @nums;
$result /= $len;
$result = sqrt $result;
}
return "$type: $result",
structured_answer => {
data => {
title => $result,
subtitle => "$type of: $_"
},
templates => {
group => 'text'
}
};
};
1;