in reply to Read file text and find fibonacci series
This appears to have been posted to Meditations, but I'm not sure if you meant it to be a question? Anyway, you're describing scanning a string looking for a pattern, which is exactly what regular expressions are good at. Ignoring the duplicate 1's, there are only 29 Fibonacci numbers with 1 to 6 digits, a regex can handle that just fine (and it would have no problem handling much more). See Building Regex Alternations Dynamically.
This code can handle huge numbers too, try changing $DIGITS to e.g. 60. And note that you can use the same regex to find sequences of numbers, e.g. (?:$re){3,} (although that doesn't check if they are consecutive in the sequence).
#!/usr/bin/env perl use warnings; use strict; my $DIGITS = 6; my %fib; { use bigint; for ( my ($f,$t)=(1,1); length($f)<=$DIGITS; ($f,$t)=($t,$f+$t) ) { my $s = "$f"; $fib{$s} = [$s]; while (length $s > 1) { chop $s; push @{$fib{$f}}, $s if exists $fib{$s}; } } } #use Data::Dump; dd \%fib; print "There are ",0+keys(%fib)," fibs with up to $DIGITS digits\n"; my ($re) = map {qr/$_/} join '|', map {quotemeta} sort { length $b <=> length $a or $b cmp $a } keys %fib; print "$re\n"; while (<DATA>) { chomp; print "Searching '$_'\n"; while (/(?=($re))./g) { print "Found ",join(', ',@{$fib{$1}})," at ",$-[0],"\n"; } } __DATA__ 496934634523123433886451447233402467622113 690168906931029935139391829792095612517948949963798093315456
Update: You appear to have edited your node to remove its content, please see How do I change/delete my post? for why you shouldn't do that. Content restored, thanks Athanasius. Also made very minor fixups.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Read file text and find fibonacci series
by vr (Curate) on Jan 03, 2018 at 00:01 UTC | |
by haukex (Archbishop) on Jan 03, 2018 at 09:00 UTC |