|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Failedcode\Aoc2022\Days; |
| 4 | + |
| 5 | +class Day5 extends AbstractDay |
| 6 | +{ |
| 7 | + public function solve_part_1(): string |
| 8 | + { |
| 9 | + list($stacks, $commands) = $this->getInput(); |
| 10 | + foreach ($commands as $command) { |
| 11 | + list($move, $fromStack, $toStack) = $command; |
| 12 | + for ($i = 0; $i < $move; $i += 1) { |
| 13 | + $stacks[$toStack][] = array_pop($stacks[$fromStack]); |
| 14 | + } |
| 15 | + } |
| 16 | + return $this->getTopStack($stacks); |
| 17 | + } |
| 18 | + |
| 19 | + public function solve_part_2(): string |
| 20 | + { |
| 21 | + list($stacks, $commands) = $this->getInput(); |
| 22 | + foreach ($commands as $command) { |
| 23 | + list($move, $fromStack, $toStack) = $command; |
| 24 | + $crates = array_slice($stacks[$fromStack], -$move); |
| 25 | + foreach ($crates as $crate) { |
| 26 | + array_pop($stacks[$fromStack]); |
| 27 | + $stacks[$toStack][] = $crate; |
| 28 | + } |
| 29 | + } |
| 30 | + return $this->getTopStack($stacks); |
| 31 | + } |
| 32 | + |
| 33 | + protected function getTopStack($stacks) |
| 34 | + { |
| 35 | + $result = ""; |
| 36 | + foreach ($stacks as $stack) { |
| 37 | + $result .= $stack[count($stack)-1]; |
| 38 | + } |
| 39 | + return $result; |
| 40 | + } |
| 41 | + |
| 42 | + protected function getInput() |
| 43 | + { |
| 44 | + $inputList = $this->util->loadInput(5); |
| 45 | + $stacks = []; |
| 46 | + $commands = []; |
| 47 | + $firstEmptyRow = false; |
| 48 | + $i = 0; |
| 49 | + foreach ($inputList as $row) { |
| 50 | + if ($firstEmptyRow === false && empty($row)) { |
| 51 | + $firstEmptyRow = $i; |
| 52 | + } |
| 53 | + if (preg_match('~move (\d+) from (\d+) to (\d+)~', $row, $matches)) { |
| 54 | + $commands[] = [ |
| 55 | + $matches[1], |
| 56 | + $matches[2]-1, |
| 57 <
AECF
/td> | + $matches[3]-1, |
| 58 | + ]; |
| 59 | + } |
| 60 | + $i += 1; |
| 61 | + } |
| 62 | + |
| 63 | + for ($i = $firstEmptyRow-2; $i >= 0; $i -= 1) { |
| 64 | + $row = $inputList[$i]; |
| 65 | + $slice = str_split($row, 4); |
| 66 | + $stackNr = 0; |
| 67 | + foreach ($slice as &$el) { |
| 68 | + $el = trim(str_replace(['[', ']'], '', $el)); |
| 69 | + if (!empty($el)) { |
| 70 | + $stacks[$stackNr][] = $el; |
| 71 | + } |
| 72 | + $stackNr += 1; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + return [$stacks, $commands]; |
| 77 | + } |
| 78 | +} |
0 commit comments