Ejemplo n.º 1
0
// function to work out the km travelled of a reindeer after n seconds
function distanceAfter($d, $s)
{
    // work out length of go/rest cycle
    $cycle = $d['duration'] + $d['rest'];
    // distance - full cycles
    $distance = floor($s / $cycle) * $d['speed'] * $d['duration'];
    // distance - remaining part cycle
    $distance += min($s % $cycle, $d['duration']) * $d['speed'];
    return intval($distance);
}
// work out who is in front each second
for ($i = 1; $i <= 2503; $i++) {
    // loop reindeer and work out how far each has travelled
    foreach ($deer as $name => $d) {
        $deer[$name]['distance'] = distanceAfter($d, $i);
    }
    // award a point to whoever is in the lead
    $furthest = 0;
    foreach ($deer as $name => $d) {
        if ($d['distance'] > $furthest) {
            $furthest = $d['distance'];
            $fastBastards = array($name);
        } elseif ($d['distance'] == $furthest) {
            $fastBastards[] = $name;
        }
    }
    // add point(s)
    foreach ($fastBastards as $jimmySpeedyPants) {
        $deer[$jimmySpeedyPants]['score']++;
    }
Ejemplo n.º 2
0
*/
// parse the input file into an array
$deer = array();
foreach (file('input/day-14.txt') as $line) {
    preg_match('/^(\\w+) can fly (\\d+) km\\/s for (\\d+) seconds, but then must rest for (\\d+) seconds\\.$/', $line, $m);
    $deer[$m[1]] = array('speed' => $m[2], 'duration' => $m[3], 'rest' => $m[4]);
}
// function to work out the km travelled of a reindeer after n seconds
function distanceAfter($d, $s)
{
    // work out length of go/rest cycle
    $cycle = $d['duration'] + $d['rest'];
    // distance - full cycles
    $distance = floor($s / $cycle) * $d['speed'] * $d['duration'];
    // distance - remaining part cycle
    $distance += min($s % $cycle, $d['duration']) * $d['speed'];
    return intval($distance);
}
// loop reindeer and work out how far each has travelled
foreach ($deer as $name => $d) {
    $deer[$name]['distance'] = distanceAfter($d, 2503);
}
// find the winner
$furthest = 0;
foreach ($deer as $d) {
    if ($d['distance'] > $furthest) {
        $furthest = $d['distance'];
    }
}
// output answer
echo 'Answer: ' . $furthest;