summary refs log tree commit diff homepage
path: root/2023
diff options
context:
space:
mode:
authorJune McEnroe <june@causal.agency>2023-12-15 20:22:24 -0500
committerJune McEnroe <june@causal.agency>2023-12-15 20:22:24 -0500
commit3c5a0b02676c04a8035ac79122eba784fecd18a0 (patch)
tree71070788fef7cbbdc0f883d5da4fe2adf1e670e2 /2023
parentSolve day 8 part 1 (diff)
downloadaoc-3c5a0b02676c04a8035ac79122eba784fecd18a0.tar.gz
aoc-3c5a0b02676c04a8035ac79122eba784fecd18a0.zip
Solve day 9 part 1
Diffstat (limited to '2023')
-rw-r--r--2023/day09.pl28
1 files changed, 28 insertions, 0 deletions
diff --git a/2023/day09.pl b/2023/day09.pl
new file mode 100644
index 0000000..5ec28b2
--- /dev/null
+++ b/2023/day09.pl
@@ -0,0 +1,28 @@
+use strict;
+use warnings;
+use List::Util qw(any);
+sub diff {
+	my @diff;
+	for my $i (0 .. $#_-1) {
+		push @diff, $_[$i+1] - $_[$i];
+	}
+	@diff;
+}
+sub extrapolate {
+	my @diffs = (\@_);
+	while (any { $_ != 0 } @{$diffs[0]}) {
+		unshift @diffs, [diff(@{$diffs[0]})];
+	}
+	push @{$diffs[0]}, 0;
+	for (1 .. $#diffs) {
+		push @{$diffs[$_]}, $diffs[$_-1]->[-1] + $diffs[$_]->[-1];
+	}
+	$diffs[-1]->[-1];
+}
+my $sum = 0;
+while (<>) {
+	chomp;
+	my @history = split(/ /);
+	$sum += extrapolate(@history);
+}
+print $sum, "\n";