### re: AoC Day 14: Chocolate Charts VIEW POST

The part 1 was super easy: I just pushed new elements to an array.

``````#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

chomp( my \$input = <> );

my @scores = (3, 7);
my @elves = (0, 1);
while (@scores < 11 + \$input) {
my \$new = \$scores[ \$elves[0] ] + \$scores[ \$elves[1] ];
push @scores, split //, \$new;
\$elves[\$_] += 1 + \$scores[ \$elves[\$_] ], \$elves[\$_] %= @scores
for 0, 1;
}
say @scores[\$input .. 9 + \$input];
``````

When I adapted the algorithm for the part 2, it took almost a minute to get the answer. To optimize it, I used strings instead of arrays of numbers (strings are not arrays in Perl).

``````#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };

chomp( my \$input = <> );

my \$score = '37';
my @elves = (0, 1);
while (length \$score < length \$input
|| -1 == rindex substr(\$score, -12), \$input
) {
my \$new = substr(\$score, \$elves[0], 1) + substr \$score, \$elves[1], 1;
\$score .= \$new;
\$elves[\$_] += 1 + substr(\$score, \$elves[\$_], 1),
\$elves[\$_] %= length \$score
for 0, 1;
}
say rindex \$score, \$input;
``````
code of conduct - report abuse