summary refs log tree commit diff homepage
diff options
context:
space:
mode:
authorJune McEnroe <june@causal.agency>2021-12-07 11:15:45 -0500
committerJune McEnroe <june@causal.agency>2021-12-07 11:15:45 -0500
commit91e0bf0f4c2b28b6a70c5770262f3972b6879857 (patch)
tree7df5909bcb1a95396e4ce963efb97dda95d04579
parentSolve day 7 part 1 (diff)
downloadaoc-91e0bf0f4c2b28b6a70c5770262f3972b6879857.tar.gz
aoc-91e0bf0f4c2b28b6a70c5770262f3972b6879857.zip
Solve day 7 part 2
-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";