adventofcode/2023/d2/d2.php

36 lines
750 B
PHP
Raw Normal View History

2023-12-02 15:18:41 +01:00
<?php
// Over-complicated because I thought they wouldn't put the cube back in the bag at first.
$FILE_NAME = "input.txt";
$sum = 0;
$fd = fopen($FILE_NAME, "r");
while($line = fgets($fd)){
$data = array();
preg_match("/Game (\d+): (.*)/", $line, $data);
$game_id = $data[1];
$hand = explode(";", $data[2]);
$valid = true;
foreach ($hand as $h) {
$bag = array(
"red" => 12,
"green" => 13,
"blue" => 14,
);
$colors = array();
preg_match_all("/(\d+) (red|green|blue)/", $h, $colors);
foreach (array_combine($colors[2], $colors[1]) as $key => $value) {
$bag[$key] = $bag[$key] - $value;
if($bag[$key] < 0){$valid = false;}
}
}
if($valid){$sum = $sum + $game_id; echo $game_id . "\n";}
}
fclose($fd);
echo $sum;