summary refs log tree commit diff homepage
path: root/2021/day07.pl
blob: a403125767eebc88a32ed6a49f39ff955dd34c66 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 = 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";