13th day both parts
This commit is contained in:
61
13/part2.php
Normal file
61
13/part2.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
||||
$coordinates = $coordinatesPrint = [];
|
||||
$folds = [];
|
||||
|
||||
foreach ($input as $line) {
|
||||
if (strstr($line, 'fold')) {
|
||||
preg_match('#fold along ([x|y])=(\d*)#', $line, $found);
|
||||
$folds[] = [$found[1], (int)$found[2]];
|
||||
} else {
|
||||
$point = explode(',', $line);
|
||||
$coordinates[] = $point;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($folds as $fold) {
|
||||
foreach ($coordinates as &$point) {
|
||||
if ($fold[0] == 'x' && $point[0] > $fold[1]) {
|
||||
$point[0] = $fold[1] * 2 - $point[0];
|
||||
}
|
||||
if ($fold[0] == 'y' && $point[1] > $fold[1]) {
|
||||
$point[1] = $fold[1] * 2 - $point[1];
|
||||
}
|
||||
}
|
||||
$coordinates = points_unique($coordinates);
|
||||
}
|
||||
|
||||
printImage($coordinates); // PGHRKLKL
|
||||
|
||||
|
||||
function points_unique($coordinates)
|
||||
{
|
||||
$tmp = [];
|
||||
$newCoordinates = [];
|
||||
foreach ($coordinates as $point) {
|
||||
if (!isset($tmp[implode(',', $point)])) {
|
||||
$newCoordinates[] = $point;
|
||||
$tmp[implode(',', $point)] = 1;
|
||||
}
|
||||
}
|
||||
return $newCoordinates;
|
||||
}
|
||||
|
||||
function printImage($coordinates)
|
||||
{
|
||||
$maxx = $maxy = 0;
|
||||
foreach ($coordinates as $point) {
|
||||
if ($point[0] > $maxx) {
|
||||
$maxx = $point[0];
|
||||
}
|
||||
if ($point[1] > $maxy) {
|
||||
$maxy = $point[1];
|
||||
}
|
||||
}
|
||||
$image = array_fill(0, $maxy + 1, array_fill(0, $maxx + 1, ' '));
|
||||
foreach ($coordinates as $point) {
|
||||
$image[$point[1]][$point[0]] = '#';
|
||||
}
|
||||
echo implode("\n", array_map(fn($line) => implode('', $line), $image));
|
||||
}
|
||||
Reference in New Issue
Block a user