]> www.fi.muni.cz Git - aoc.git/blob - 2015/26.pl
Year 2015
[aoc.git] / 2015 / 26.pl
1 #!/usr/bin/perl -w
2
3 use v5.16;
4 use strict;
5
6 my %rules;
7 my %persons;
8
9 while (<>) {
10         my ($p1, $sign, $score, $p2) = /(\w+) would (\w+) (\d+) happiness units? by sitting next to (\w+)\./;
11         $sign = ($sign eq 'gain') ? 1 : -1;
12         $rules{$p1}{$p2} = $sign * $score;
13         $persons{$p1}++;
14         $persons{$p2}++;
15 }
16
17 $persons{myself}++;
18 for my $p (keys %persons) {
19         $rules{myself}{$p} = 0;
20         $rules{$p}{myself} = 0;
21 }
22
23 my $max;
24 sub perm {
25         my ($done, $rest) = @_;
26
27         if (@$rest) {
28                 for my $i (0 .. $#$rest) {
29                         my @nd = @$done;
30                         my @nr = @$rest;
31                         push @nd, splice @nr, $i, 1;
32                         perm(\@nd, \@nr);
33                 }
34         } else {
35                 my $score;
36                 for my $i (0 .. $#$done) {
37                         my $self = $done->[$i];
38                         my @neigh = ($done->[$i-1], $done->[$i == $#$done ? 0 : $i+1]);
39                         for my $n (@neigh) {
40                                 $score += $rules{$self}{$n};
41                         }
42                 }
43                 $max = $score if !defined $max || $max < $score;        
44         }
45 }
46
47 perm([], [ keys %persons ]);
48 say $max;
49