zeroclickinfo-goodies/lib/DDG/Goodie/RandomNumber.pm

54 lines
1.2 KiB
Perl
Raw Normal View History

package DDG::Goodie::RandomNumber;
2014-08-30 11:31:50 -07:00
# ABSTRACT: generate a random number in the requested range.
use strict;
use DDG::Goodie;
zci answer_type => 'rand';
zci is_cached => 0;
triggers start => 'rand','random','number';
handle query_lc => sub {
srand();
# Random number.
# q_check (as opposed to q_internal) Allows for decimals.
2014-10-15 07:44:27 -07:00
return unless ($_ =~ /^\!?(?:rand(?:om|)(?: num(?:ber|)|)(?: between|))( [\d\.]+|)(?: and|)( [\d\.]+|)$/i);
2014-10-15 07:44:27 -07:00
my $start = $1 || 0;
my $end = $2 || 0;
2014-10-15 07:44:27 -07:00
$start = 1000000000 if $start > 1000000000;
$start = 0 if $start < 0;
$start += 0;
2014-10-15 07:44:27 -07:00
$end = 1000000000 if $end > 1000000000;
$end = 0 if $end < 0;
$end = 1 if !$end;
$end += 0;
2014-10-15 07:44:27 -07:00
($end, $start) = ($start, $end) if ($start > $end);
my $valDiff = $end - $start;
2014-10-15 07:44:27 -07:00
my $rand = rand;
if ($start && $end || $valDiff > 1) {
2015-08-31 04:39:31 -07:00
$rand *= ($valDiff + 1);
2014-10-15 07:44:27 -07:00
$rand = int($rand) + $start;
}
2014-10-15 07:44:27 -07:00
return "$rand (random number)",
2014-10-15 07:44:27 -07:00
structured_answer => {
data => {
title => $rand,
subtitle => "Random number between $start - $end"
},
templates => {
group => "text",
}
2014-10-15 07:44:27 -07:00
};
};
2014-08-30 11:31:50 -07:00
1;