function generate_all_orders($items, $step = 0)
{
    if (count($items) === 1) {
        return [$items];
    }
    $paths = [];
    foreach ($items as $item) {
        $index = array_search($item, $items);
        $newItems = $items;
        array_splice($newItems, $index, 1);
        $nextPaths = generate_all_orders($newItems, $step + 1);
        foreach ($nextPaths as $k => $path) {
            array_unshift($nextPaths[$k], $item);
            $paths[] = $nextPaths[$k];
        }
    }
    return $paths;
}
Example #2
0
<?php

require_once 'inc/_include_all.php';
$input = file('input.txt', FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
$info = parse_input($input);
$infoMap = [];
$uniques = [];
foreach ($info as $piece) {
    $uniques[$piece->getSubject()] = true;
    if (!isset($infoMap[$piece->getSubject()])) {
        $infoMap[$piece->getSubject()] = [];
    }
    $infoMap[$piece->getSubject()][$piece->getObject()] = $piece->getHappinessDelta();
}
$uniques = array_keys($uniques);
$allorders = generate_all_orders($uniques);
$maxArrangement = null;
$maxHappiness = 0;
foreach ($allorders as $order) {
    $happiness = calculate_total_happiness($order, $infoMap);
    if ($happiness > $maxHappiness) {
        $maxHappiness = $happiness;
        $maxArrangement = $order;
    }
}
var_dump($maxArrangement);
echo PHP_EOL, "Happiness: ", $maxHappiness, PHP_EOL;
Example #3
0
<?php

require_once 'inc/DistanceMapper.class.php';
require_once 'inc/generate_all_orders.func.php';
$file = file('input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$map = new DistanceMapper();
foreach ($file as $line) {
    preg_match('/(\\w+) to (\\w+) = (\\d+)/i', $line, $parts);
    $a = $parts[1];
    $b = $parts[2];
    $distance = $parts[3];
    $map->setDistance($a, $b, $distance);
}
$cities = $map->getCities();
$paths = array();
$paths = generate_all_orders($cities);
$longestDistance = -INF;
$longestDistancePath = null;
foreach ($paths as $path) {
    $distance = 0;
    for ($i = 0; $i < count($path) - 1; ++$i) {
        $distance += $map->getDistance($path[$i], $path[$i + 1]);
    }
    if ($distance > $longestDistance) {
        $longestDistance = $distance;
        $longestDistancePath = implode(' -> ', $path);
    }
}
echo $longestDistancePath . ' = ' . $longestDistance;