Created
December 10, 2023 15:18
-
-
Save mrbellek/524f0764339b729da6fa457baafa4236 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
$input = file('input.txt'); | |
//$input = file('sample.txt'); | |
$times = array_filter(explode(' ', trim(substr($input[0], strpos($input[0], ':') + 1)))); | |
$distances = array_filter(explode(' ', trim(substr($input[1], strpos($input[1], ':') + 1)))); | |
$races = array_combine($times, $distances); | |
$part1Answer = 1; | |
foreach ($races as $time => $distance) { | |
$part1Answer *= findPossibleWinningRaceCount(intval($time), intval($distance)); | |
} | |
printf('Part 1 answer: %s' . PHP_EOL, $part1Answer); | |
$time = str_replace(' ', '', substr($input[0], strpos($input[0], ':') + 1)); | |
$distance = str_replace(' ', '', substr($input[1], strpos($input[1], ':') + 1)); | |
printf('Part 2 answer: %s' . PHP_EOL, findPossibleWinningRaceCount(intval($time), intval($distance))); | |
function findPossibleWinningRaceCount(int $timeInMs, int $distanceInMm): int | |
{ | |
printf('Finding ways to beat record of %d mm in %d ms...' . PHP_EOL, $distanceInMm, $timeInMs); | |
$possibleWinCount = 0; | |
for ($holdTime = 1; $holdTime < $timeInMs; $holdTime++) { | |
$raceTime = $timeInMs - $holdTime; | |
$raceDistance = $raceTime * $holdTime; | |
if ($raceDistance > $distanceInMm) { | |
$possibleWinCount++; | |
//printf('winning: holding button for %d ms gives a distance of %s!' . PHP_EOL, $raceTime, $raceDistance); | |
} | |
} | |
if ($possibleWinCount === 0) { | |
printf('none found :(' . PHP_EOL); | |
} else { | |
printf('there are %d ways' . PHP_EOL, $possibleWinCount); | |
} | |
return $possibleWinCount; | |
} | |
function dd($a, $b = null, $c = null, $d = null): void | |
{ | |
die(var_dump($a, $b, $c, $d)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment