advent_of_code_2022/day_5/part_1.php
2022-12-06 10:56:05 +01:00

40 lines
1.0 KiB
PHP

<?php
[$columns, $movements] = explode("\n\n", file_get_contents('./input.txt'));
$columns = parseColumns($columns);
$movements = explode("\n", $movements);
foreach ($movements as $movement) {
preg_match('/^move (\d+) from (\d+) to (\d+)$/', $movement, $matches);
[, $number, $from, $to] = $matches;
for ($i = 0; $i < $number; $i++) {
$element = array_pop($columns[$from]);
if ($element === null) {
break;
}
$columns[$to][] = $element;
}
}
echo implode(array_map('array_pop', $columns));
function parseColumns(string $columns)
{
$parsed_columns = [];
$rows = array_map('str_split', explode("\n", $columns));
array_unshift($rows, null);
$rows = array_map(...$rows);
$rows = array_map('array_reverse', $rows);
foreach ($rows as $row) {
$number = array_shift($row);
if (!is_numeric($number) || empty($number)) {
continue;
}
$parsed_columns[$number] = array_filter($row, fn($cell) => !empty(trim($cell)));
}
return $parsed_columns;
}