aoc2015

Advent of Code 2015 solutions in Perl.
git clone git://git.samirparikh.com/aoc2015
Log | Files | Refs | README

day10.pl (1248B) - raw


      1 #!/usr/local/bin/perl
      2 # day 2015-10
      3 
      4 use strict;
      5 use warnings;
      6 use v5.32;
      7 
      8 my $string = 1113122113;
      9 
     10 #
     11 # solution inspired by Abigail at:
     12 # https://github.com/Abigail/AdventOfCode2015/blob/master/Day_10/look-and-say.pl
     13 #
     14 
     15 sub next_string {
     16     my $string = shift;
     17     my $result = "";
     18 
     19     while ( $string =~ /\G((.)\2*)/g) {
     20 
     21 # the capture variable $1 represents what is matched in the outer most set of
     22 # parentheses:  (.)\2*
     23 # this matches for any number (.) followed by zero or more occurrences (*) of
     24 # itself using a back reference (\2).
     25 # the capture variable $2 represents the number.  The length of $1 represents
     26 # the number of times that number was captured.  To see how it works, uncomment
     27 # the following line:
     28 #        say length $1, " ", $2, "s";
     29 # the \G anchor can be used to start the next match on the same string where the
     30 # last match left off.  For more information, please see:
     31 # https://perldoc.perl.org/perlfaq6#What-good-is-%5CG-in-a-regular-expression?
     32 
     33         $result .= ( length $1 ) . $2;
     34     }
     35 
     36     return $result;
     37 }
     38 
     39 $string = next_string( $string ) foreach ( 1 .. 40 );
     40 say "part 1: ", length $string;
     41 
     42 $string = next_string( $string ) foreach ( 1 .. 10 ); # to reach 50 iterations
     43 say "part 2: ", length $string;