Skip to content

Instantly share code, notes, and snippets.

@pronto2000
Created December 6, 2022 13:01
Show Gist options
  • Save pronto2000/d7cf8130130aa971aba32aecf201a966 to your computer and use it in GitHub Desktop.
Save pronto2000/d7cf8130130aa971aba32aecf201a966 to your computer and use it in GitHub Desktop.
2022 Advent Stacks
<?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";
@pronto2000
Copy link
Author

pronto2000 commented Dec 6, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment