]> www.fi.muni.cz Git - aoc.git/blob - 2015/25.pl
Day 25: examining the input
[aoc.git] / 2015 / 25.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 my $max;
18 sub perm {
19         my ($done, $rest) = @_;
20
21         if (@$rest) {
22                 for my $i (0 .. $#$rest) {
23                         my @nd = @$done;
24                         my @nr = @$rest;
25                         push @nd, splice @nr, $i, 1;
26                         perm(\@nd, \@nr);
27                 }
28         } else {
29                 my $score;
30                 for my $i (0 .. $#$done) {
31                         my $self = $done->[$i];
32                         my @neigh = ($done->[$i-1], $done->[$i == $#$done ? 0 : $i+1]);
33                         for my $n (@neigh) {
34                                 $score += $rules{$self}{$n};
35                         }
36                 }
37                 $max = $score if !defined $max || $max < $score;        
38         }
39 }
40
41 perm([], [ keys %persons ]);
42 say $max;
43