challenges

my solutions to various "programming challenge" problems
git clone https://wehaveforgeathome.hates.computer/challenges.git
Log | Files | Refs | LICENSE

level1.pl (720B)


      1 #!/usr/bin/perl
      2 
      3 open(my $file, 'level1.txt');
      4 my $text = <$file>;
      5 close($file);
      6 
      7 chomp($text);
      8 
      9 # generate list of all substrings
     10 my %strings;
     11 
     12 sub gen_substrings {
     13   my $string = shift;
     14   if (defined($strings{$string})) {
     15     return ();
     16   }
     17   $strings{$string} = 1;
     18   my $l = length($string);
     19   if ($l == 3) { return ($string); }
     20 
     21   my $first = substr($string, 0, $l - 1);
     22   my $last = substr($string, 1);
     23   return ($string, gen_substrings($first), gen_substrings($last));
     24 }
     25 
     26 my @substrings = gen_substrings($text);
     27 
     28 # filter palindrones
     29 my @palindrones = grep { $_ eq reverse($_) } @substrings;
     30 
     31 # sort by length, take first
     32 my @sorted = sort { length($b) <=> length($a) } @palindrones;
     33 
     34 print shift(@sorted) . "\n";