/
day13.php
58 lines (51 loc) · 1.3 KB
/
day13.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
ini_set('memory_limit','512M');
$in = file('input/day13.txt');
$regex = '/(\w+) would (gain|lose) (\d+) happiness units by sitting next to (\w+)./';
$sit = [];
foreach($in as $row) {
if (!preg_match($regex, $row, $match)) continue;
$who = $match[1];
$points = $match[2] == 'gain' ? intval($match[3]) : intval('-'.$match[3]);
$nextTo = $match[4];
$sit[$who][$nextTo] = $points;
}
//permutations
function permute($arr) {
$result = [];
$rec = function($res, $rest) use (&$result, &$rec) {
if (empty($rest)) {
$result[] = $res;
return;
}
foreach ($rest as $val) {
$newRes = $res;
$newRes[] = $val;
$rec($newRes, array_diff($rest, $newRes));
}
};
$rec([], $arr);
return $result;
}
$people = array_keys($sit);
$people[] = 'Self';
$permutations = permute($people);
function calcScore($seats) {
global $sit;
$len = count($seats);
$score = 0;
for ($i=0; $i<$len; $i++) {
$self = $seats[$i];
$left = $seats[($i-1+$len)%$len];
$right = $seats[($i+1+$len)%$len];
if ($left !== 'Self') $score += $sit[$self][$left];
if ($right !== 'Self') $score += $sit[$self][$right];
}
return $score;
}
$scores = [];
foreach($permutations as $perm) {
$idx = implode(', ', $perm);
$scores[$idx] = calcScore($perm);
}
var_dump(max($scores));