advent_of_code_2022/day_5/part_2.php

34 lines
1.0 KiB
PHP
Raw Normal View History

2022-12-06 10:56:05 +01:00
<?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;
$elements = array_splice($columns[$from], count($columns[$from]) - $number, $number);
$columns[$to] = array_merge($columns[$to], $elements);
}
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;
}