Example #1
0
function returnHappiness($input)
{
    $table = processInput($input);
    $results = [];
    $combinations = permute(array_keys($table));
    foreach ($combinations as $c) {
        $happiness = 0;
        for ($i = 0; $i < strlen($c); $i++) {
            $personA = $c[$i];
            $personB = $i === strlen($c) - 1 ? $c[0] : $c[$i + 1];
            $happiness = happiness($happiness, $table[$personA][$personB]);
            $happiness = happiness($happiness, $table[$personB][$personA]);
        }
        // echo $c . ': ' . $happiness . '<br>';
        $results[] = $happiness;
    }
    return $results;
}
Example #2
0
        $left = $currentPerson;
        $key = implode('.', $set);
        $scores[$key] = 0;
        // Build a scores chart
        foreach ($set as $right) {
            $scores[$key] += $map[$left][$right];
            $scores[$key] += $map[$right][$left];
            $left = $right;
        }
    }
    return max($scores);
}
$handle = fopen("input.txt", "r");
$map = [];
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        if (preg_match('/^([a-z]+) would (gain|lose) ([0-9]+) happiness units by sitting next to ([a-z]+).$/i', trim($line), $matches)) {
            $map[$matches[1]][$matches[4]] = ($matches[2] === 'gain' ? 1 : -1) * $matches[3];
        }
    }
    fclose($handle);
}
// Add yourself to the map
foreach ($map as $key => $value) {
    $map[$key]['me'] = 0;
    // Me next to another person
    $map['me'][$key] = 0;
    // Another person next to me
}
echo 'Max ammount of happiness is: ' . happiness($map) . PHP_EOL;
Example #3
0
<?php

$input = file_get_contents('day13.txt');
$lines = explode("\r\n", $input);
$lines = array_filter($lines);
$map = rulesToMap($lines);
printf('ans#13.1: %u' . PHP_EOL, happiness($map));
$me = 'Me';
foreach ($map as $person => $value) {
    $map[$person][$me] = 0;
    $map[$me][$person] = 0;
}
printf('ans#13.2: %s' . PHP_EOL, happiness($map));
function rulesToMap($lines)
{
    $map = [];
    foreach ($lines as $line) {
        $words = explode(' ', $line);
        $person = $words[0];
        $neighbour = substr(end($words), 0, -1);
        $sign = $words[2] == 'gain' ? 1 : -1;
        $happiness = $words[3] * $sign;
        $map[$person][$neighbour] = $happiness;
    }
    return $map;
}
function happiness($map)
{
    $solved = [];
    $ppl = array_keys($map);
    $start = $ppl[0];