Fibonacci: use structured answer.

master
Matt Miller 2014-10-14 18:21:34 +02:00
parent 53ffe0c3b6
commit 191b2779cc
2 changed files with 37 additions and 17 deletions

View File

@ -7,8 +7,9 @@ use DDG::Goodie;
use Lingua::EN::Numbers::Ordinate qw(ordsuf);
triggers any => 'fib', 'fibonacci';
zci is_cached => 1;
zci answer_type => 'fibonacci';
zci is_cached => 1;
primary_example_queries 'fib 7';
secondary_example_queries 'fibonacci 33';
@ -19,23 +20,28 @@ code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DD
topics 'math';
category 'calculations';
my @fib = (0, 1);
handle remainder => sub {
s/^\s+//;
s/\s+$//;
return unless /^(?:what(?:'s| is) the )?(\d+)(?:th|rd|st)?(?: number)?(?: in the (?:series|sequence))?\??$/ && $1 <= 1470;
my @fib;
my $n = $1;
$#fib = $n;
$fib[0] = 0;
$fib[1] = 1;
return unless /^(?:what(?:'s| is) the )?(?<which>\d+)(?:th|rd|st)?(?: number)?(?: in the (?:series|sequence))?\??$/ && $1 <= 1470;
my $n = $+{'which'};
# Instead of calling a typical recursive function,
# use simple dynamic programming to improve performance
for my $i (2..$#fib) {
$fib[$i] = $fib[$i - 1] + $fib[$i - 2];
if ($#fib < $n) {
for my $i ($#fib .. $n) {
$fib[$i] = $fib[$i - 1] + $fib[$i - 2];
}
}
my $suf = ordsuf($_);
my $suf = ordsuf($n);
return "The $n$suf fibonacci number is ${fib[$n]} (assuming f(0) = 0).",
html => "The $n<sup>$suf</sup> fibonacci number is ${fib[$n]} (assuming f(0) = 0).";
structured_answer => {
input => [$n . $suf],
operation => 'Fibonacci number',
result => $fib[$n],
};
};
1;

View File

@ -6,14 +6,28 @@ use Test::More;
use DDG::Test::Goodie;
zci answer_type => 'fibonacci';
zci is_cached => 1;
zci is_cached => 1;
ddg_goodie_test(
[qw(DDG::Goodie::Fibonacci)],
'fib 7' => test_zci('The 7th fibonacci number is 13 (assuming f(0) = 0).',
html => 'The 7<sup>th</sup> fibonacci number is 13 (assuming f(0) = 0).'),
'fibonacci 33' => test_zci('The 33rd fibonacci number is 3524578 (assuming f(0) = 0).',
html => 'The 33<sup>rd</sup> fibonacci number is 3524578 (assuming f(0) = 0).'),
[qw(DDG::Goodie::Fibonacci)],
'fib 7' => test_zci(
'The 7th fibonacci number is 13 (assuming f(0) = 0).',
structured_answer => {
input => ['7th'],
operation => 'Fibonacci number',
result => 13
}
),
'fibonacci 33' => test_zci(
'The 33rd fibonacci number is 3524578 (assuming f(0) = 0).',
structured_answer => {
input => ['33rd'],
operation => 'Fibonacci number',
result => 3524578
}
),
'tell a fib' => undef,
'what are fibonacci numbers?' => undef,
);
done_testing;