in reply to Read file text and find fibonacci series
Hello darkblackblue,
As the fellow Monks say this looks like a school assignment. Well I could suggest another approach to your problem but it only contains half of the solution, I have left the rest for you to solve.
Sample of code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Math::Fibonacci qw( isfibonacci ); my $string = '377'; sub mySubString { my ($string, $offset, $length) = @_; return substr $string, $offset, $length; } sub fibonacciCompare { my ($s, $iteration) = @_; my @matched; for (1..length($s)) { my $inToCompare = mySubString($s, $iteration, $_); my $fibonacci = isfibonacci($inToCompare); push @matched, "Matched: $inToCompare" if ($fibonacci); } return \@matched if $matched[0]; } my $final = fibonacciCompare($string, 0); print Dumper $final if $final; __END__ $ perl test.pl $VAR1 = [ 'Matched: 3', 'Matched: 377' ];
I used different hard coded input instead of reading your data from your file but you get the point that the input is data from your file. What I am doing on this sample of code is comparing the string part by part as you wanted with a list of fibonacci numbers. The module that I am using is Math::Fibonacci. What the script does not do is to compare the numbers by subtracting the elements one by one until the end as you described. I have left this part out.
Update: I just observed that the darkblackblue has asked the question since the 28th December. I assume that he/she was not able to resolve it. Just to add complete answer to the question for future reference see sample of code bellow:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use feature 'say'; use Math::Fibonacci qw( isfibonacci ); sub mySubString { my ($string, $offset, $length) = @_; return substr $string, $offset, $length; } sub fibonacciCompare { my ($s, $offset) = @_; my @matched; for (1..length($s)) { my $inToCompare = mySubString($s, $offset, $_); say $inToCompare; my $fibonacci = isfibonacci($inToCompare); push @matched, "Matched: $inToCompare" if ($fibonacci); } return \@matched if $matched[0]; } my %HoA; my @AoA; my $string = '377'; for (1..length($string)) { my $fibonacci = fibonacciCompare($string, 0); push @AoA, $fibonacci; $HoA{$string} = $fibonacci; $string = substr $string, 1; } print Dumper \@AoA; print Dumper \%HoA; __END__ $ perl test.pl 3 37 377 7 77 7 $VAR1 = [ [ 'Matched: 3', 'Matched: 377' ], undef, undef ]; $VAR1 = { '77' => undef, '7' => undef, '377' => [ 'Matched: 3', 'Matched: 377' ] };
Hope this helps, BR.
|
|---|