summary refs log tree commit diff homepage
diff options
context:
space:
mode:
-rw-r--r--2021/day07.pl15
1 files changed, 13 insertions, 2 deletions
diff --git a/2021/day07.pl b/2021/day07.pl
index 209bcb2..a403125 100644
--- a/2021/day07.pl
+++ b/2021/day07.pl
@@ -1,7 +1,18 @@
 use strict;
 use warnings;
+use List::Util qw(min max sum);
 my @crabs = sort { $a <=> $b } split(/,/, <>);
 my $median = $crabs[@crabs / 2];
-my $cost = 0;
-$cost += abs($_ - $median) for @crabs;
+my $cost = sum(map { abs($_ - $median) } @crabs);
 print "$cost\n";
+sub cost {
+	my ($to, $from) = @_;
+	my $n = abs($from - $to);
+	$n * ($n + 1) / 2;
+}
+sub totalCost {
+	my $x = shift;
+	sum(map { cost($x, $_) } @_);
+}
+my $min = min(map { totalCost($_, @crabs) } min(@crabs)..max(@crabs));
+print "$min\n";