summary refs log tree commit diff homepage
path: root/2023/day09.pl
diff options
context:
space:
mode:
Diffstat (limited to '')
-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";