Created
December 6, 2022 13:01
-
-
Save pronto2000/d7cf8130130aa971aba32aecf201a966 to your computer and use it in GitHub Desktop.
2022 Advent Stacks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$fp = fopen('input.txt', 'r'); | |
$data = []; | |
$cmds = []; | |
while (($line = fgets($fp, 64)) !== false) { | |
if (strpos($line, '[') !== false) { | |
$data[] = str_split($line); | |
} elseif (strpos($line, 'move') !== false) { | |
preg_match('/move (\d+) from (\d+) to (\d+)/', $line, $matches); | |
$cmds[] = $matches; | |
} | |
} | |
$stacks = []; | |
for ($i = 0; $i < sizeof($data[0]) / 4; $i++) { | |
$stacks[] = trim(strrev(implode('', array_column($data, $i * 4 + 1)))); | |
} | |
foreach ($cmds as $cmd) { | |
$stacks[$cmd[3] - 1] .= strrev(substr($stacks[$cmd[2] - 1], $cmd[1] * -1)); | |
$stacks[$cmd[2] - 1] = substr($stacks[$cmd[2] - 1], 0, $cmd[1] * -1); | |
} | |
$output = ''; | |
foreach ($stacks as $stack) { | |
$output .= substr($stack, -1); | |
} | |
echo "$output\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Praktikas saaks selle koodijupi veel umbes poole lühemaks optimeerida. Esiteks on sisendafail alati üks, mis võimaldab osa asju hardcodeda ning teiseks on korralduste ajaks andmed juba olemas ning nende protsessimine võiks toimuda koos lugemisega. Pluss paar nipet-näpet asja veel.