<?php
//
//$maxRed = 12;
//$maxGreen = 13;
//$maxBlue = 14;
//
//$lines = file($_SERVER["DOCUMENT_ROOT"]."/input2.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = [
'Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green',
'Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue',
'Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red',
'Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red',
'Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green',
];
//$limits = [
// 'red' => 12,
// 'green' => 13,
// 'blue' => 14,
//];
$limits = [12, 13, 14];
foreach ($lines as $game)
{
$colonPos = strpos($game, ':');
$sets = explode(';', trim(substr($game, $colonPos + 1)));
$ok = true;
foreach ($sets as $set)
{
if (!$ok)
{
break;
}
$picks = explode(',', $set);
$pickSum = [0,0,0];
foreach ($picks as $pick)
{
$pickArray = explode(' ', trim($pick));
$attempt = (int)$pickArray[0];
$color = $pickArray[1];
switch($color)
{
case 'red':
$pickSum[0] += $attempt;
break;
case 'green':
$pickSum[1] += $attempt;
break;
case 'blue':
$pickSum[2] += $attempt;
break;
}
if ($limits > $pickSum)
{
$ok = false;
break 2;
}
}
preg_match('/\d+/', substr($game, 0, $colonPos), $matches);
var_dump($matches);
}
}
preferences:
25.04 ms | 409 KiB | 5 Q