sol2.pl (940B) [raw]
1 #!/usr/bin/env perl 2 use strict; 3 use warnings; 4 5 use List::Util qw(min max); 6 7 my $invalid = `./sol1.pl input`; # cheers 8 die "$!" if $?; 9 10 my @nums; 11 { 12 local $/; 13 open(my $fh, '<', 'input') or die "$!"; 14 @nums = split("\n", <$fh>); 15 } 16 17 # IDEA: caterpillar slide 18 # - inch front forward until > invalid 19 # - inch back forward until < invalid 20 # if at any point = invalid, we win 21 my $sum = 0; 22 my @mem; 23 24 print "GOAL: $invalid\n"; 25 for my $n (@nums) { 26 printf "DBG> n: %d, sum: %d, wind: %d\n", $n, $sum, scalar @mem; 27 if ($sum == $invalid) { 28 my $result = min(@mem) + max(@mem); 29 print "$result\n"; 30 exit 0; 31 } 32 33 # move that butt forward until we can add $n without overflowing 34 while (($sum + $n) > $invalid) { 35 $sum -= shift(@mem); 36 if (!@mem) { 37 # impossible, too big 38 exit(1); 39 } 40 } 41 # scooch forward! 42 $sum += $n; 43 push(@mem, $n); 44 } 45 46 exit 1;