Skip to content

Instantly share code, notes, and snippets.

@mrbellek
Last active December 7, 2023 15:03
Show Gist options
  • Save mrbellek/a76c3f3dc0809137f3f9c654cdf2fbf9 to your computer and use it in GitHub Desktop.
Save mrbellek/a76c3f3dc0809137f3f9c654cdf2fbf9 to your computer and use it in GitHub Desktop.
Advent of Code 2023 - day 2
<?php
declare(strict_types=1);
$input = file('input.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$maxRed = 12;
$maxGreen = 13;
$maxBlue = 14;
$validCount = 0;
$sumOfGameIds = 0;
$sumOfGamePowers = 0;
foreach ($input as $line) {
$gameInfo = getGameInfo($line);
/*if (isGamePossible($gameInfo, $maxRed, $maxGreen, $maxBlue)) {
$sumOfGameIds += key($gameInfo);
$validCount++;
}*/
$gamePower = getGamePower($gameInfo);
$sumOfGamePowers += $gamePower;
}
/*printf('Processed %d games, but only %d were possible with given restrictions, and the sum of game ids was %d.' . PHP_EOL,
count($input),
$validCount,
$sumOfGameIds
);*/
printf('Processed %d games, by their powers combined we got %s' . PHP_EOL, count($input), $sumOfGamePowers);
function getGamePower(array $gameInfo): int
{
$gamePower = 1;
$highestGreen = 0;
$highestBlue = 0;
$highestRed = 0;
foreach ($gameInfo as $id => $games) {
foreach ($games as $game) {
$highestGreen = max($highestGreen, $game['green'] ?? 0);
$highestBlue = max($highestBlue, $game['blue'] ?? 0);
$highestRed = max($highestRed, $game['red'] ?? 0);
}
}
return $highestRed * $highestBlue * $highestGreen;
}
function getGameInfo(string $line): array
{
$gameInfo = [];
$gameId = intval(str_replace('Game ', '', $line));
$games = explode(';', substr($line, strpos($line, ':') + 1));
foreach ($games as $game) {
$grabs = explode(',', $game);
$singleGameInfo = [];
foreach ($grabs as $grab) {
$numAndColour = explode(' ', trim($grab));
$singleGameInfo[$numAndColour[1]] = $numAndColour[0];
}
$gameInfo[$gameId][] = $singleGameInfo;
}
return $gameInfo;
}
function isGamePossible(array $gamesInfo, int $maxRed, int $maxGreen, int $maxBlue): bool
{
foreach ($gamesInfo as $id => $games) {
foreach ($games as $game) {
if (($game['green'] ?? 0) > $maxGreen ||
($game['red'] ?? 0) > $maxRed ||
($game['blue'] ?? 0) > $maxBlue
) {
return false;
}
}
}
return true;
}
function dd($a, $b = null, $c = null, $d = null) {
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