aoc2018/day3/main.php

101 lines
2.3 KiB
PHP

<?php
// https://adventofcode.com/2018/day/2
function puzzle1(array $claims) : int
{
$matrix = [];
foreach ($claims as $claim) {
preg_match('/#\d+\s@\s(\d+),(\d+):\s(\d+)x(\d+)/', $claim, $matches);
$coordX = $matches[1];
$coordY = $matches[2];
$sizeX = $matches[3];
$sizeY = $matches[4];
for ($i = $coordX; $i < $coordX + $sizeX; $i++) {
for ($j = $coordY; $j < $coordY + $sizeY; $j++) {
$matrix[$i][$j] += 1;
}
}
}
$return = 0;
foreach ($matrix as $row) {
foreach ($row as $column) {
if ($column > 1) {
++$return;
}
}
}
return $return;
}
function puzzle2(array $claims) : int
{
// Hooray for inefficient code
ini_set('memory_limit', '-1');
$matrix = [];
foreach ($claims as $claim) {
preg_match('/#(\d+)\s@\s(\d+),(\d+):\s(\d+)x(\d+)/', $claim, $matches);
$claimNr = $matches[1];
$coordX = $matches[2];
$coordY = $matches[3];
$sizeX = $matches[4];
$sizeY = $matches[5];
for ($i = $coordX; $i < $coordX + $sizeX; $i++) {
for ($j = $coordY; $j < $coordY + $sizeY; $j++) {
$matrix[$i.'x'.$j][] = $claimNr;
}
}
}
$blacklistIds = [];
foreach ($matrix as $key => $column) {
if (count($column) > 1) {
$blacklistIds = array_unique(array_merge($blacklistIds, $column));
unset($matrix[$key]);
}
}
foreach ($matrix as $key => $column) {
if (in_array($column[0], $blacklistIds)) {
unset($matrix[$key]);
}
}
foreach ($matrix as $column) {
return $column[0];
}
return -1;
}
echo 'First challange sample:'.PHP_EOL;
echo puzzle1([
'#1 @ 1,3: 4x4',
'#2 @ 3,1: 4x4',
'#3 @ 5,5: 2x2'
]).PHP_EOL; // 3
echo 'First challange solution:'.PHP_EOL;
echo puzzle1(explode(PHP_EOL, trim(file_get_contents(dirname(__FILE__).'/input.txt')))).PHP_EOL.PHP_EOL;
echo 'Second challange sample:'.PHP_EOL;
echo puzzle2([
'#1 @ 1,3: 4x4',
'#2 @ 3,1: 4x4',
'#3 @ 5,5: 2x2'
]).PHP_EOL; // 3
echo 'Second challange solution:'.PHP_EOL;
echo puzzle2(explode(PHP_EOL, trim(file_get_contents(dirname(__FILE__).'/input.txt')))).PHP_EOL.PHP_EOL;