Skip to content

Commit 6669e10

Browse files
committed
Day5
1 parent 7bad875 commit 6669e10

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed

src/Days/Day5.php

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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+
$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

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy