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

47 lines
1.3 KiB
Perl
Raw Normal View History

2013-01-23 13:53:53 -08:00
package DDG::Goodie::Fibonacci;
# ABSTRACT: n-th Fibonacci number
2013-01-23 13:53:53 -08:00
use strict;
use DDG::Goodie;
2013-01-24 01:20:34 -08:00
use Lingua::EN::Numbers::Ordinate qw(ordsuf);
2013-01-23 13:53:53 -08:00
triggers any => 'fib', 'fibonacci';
2014-10-14 09:21:34 -07:00
2013-01-23 13:53:53 -08:00
zci answer_type => 'fibonacci';
2014-10-14 09:21:34 -07:00
zci is_cached => 1;
2013-01-23 13:53:53 -08:00
primary_example_queries 'fib 7';
secondary_example_queries 'fibonacci 33';
description 'Returns the n-th element of Fibonacci sequence';
2015-01-07 10:37:42 -08:00
attribution github => ['https://github.com/koosha--', 'koosha--'];
2013-01-23 13:53:53 -08:00
code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/Fibonacci.pm';
topics 'math';
2013-05-28 15:56:41 -07:00
category 'calculations';
2013-01-23 13:53:53 -08:00
2014-10-14 09:21:34 -07:00
my @fib = (0, 1);
2013-01-23 13:53:53 -08:00
handle remainder => sub {
s/^\s+//;
s/\s+$//;
2014-10-14 09:21:34 -07:00
return unless /^(?:what(?:'s| is) the )?(?<which>\d+)(?:th|rd|st)?(?: number)?(?: in the (?:series|sequence))?\??$/ && $1 <= 1470;
my $n = $+{'which'};
2013-01-23 13:53:53 -08:00
# Instead of calling a typical recursive function,
# use simple dynamic programming to improve performance
2014-10-14 09:21:34 -07:00
if ($#fib < $n) {
for my $i ($#fib .. $n) {
$fib[$i] = $fib[$i - 1] + $fib[$i - 2];
}
2013-01-23 13:53:53 -08:00
}
2014-10-14 09:21:34 -07:00
my $suf = ordsuf($n);
return "The $n$suf fibonacci number is ${fib[$n]} (assuming f(0) = 0).",
2014-10-14 09:21:34 -07:00
structured_answer => {
input => [$n . $suf],
operation => 'Fibonacci number',
result => $fib[$n],
};
2013-01-23 13:53:53 -08:00
};
1;