Created
September 3, 2014 12:53
-
-
Save pqr/6f4cb7fe36ffecd4be7e to your computer and use it in GitHub Desktop.
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 | |
/* php скрипт в императивном стиле для статьи http://pqr7.wordpress.com/2014/09/03/haskell-vs-php/ */ | |
function splitPerBlock(array $lines) { | |
$blocks = []; | |
//Перебираем линии, отрезая от начала массива $lines найденные блоки. В итоге массив $lines станет пустым, а массив | |
//$linesPerBlock наполнится данными | |
while ($lines) { | |
//Если текущий блок начинается со строки, которая содержит "Container No.", удаляем эту строку | |
if (strpos($lines[0], 'Container No.') !== false) { | |
array_shift($lines); | |
} | |
//Для того, чтобы сформировать очередной блок нужно как минимум 20 линий. Если осталось меньше линий - заканчиваем | |
//алгоритм и возвращаем накопленные блоки | |
if (count($lines) < 20) { | |
return $blocks; | |
} | |
//Отрезаем от $lines 20 линий из начала массива и сохраняем в результирующий массив $blocks | |
$first20Lines = array_splice($lines, 0, 20); | |
$blocks[] = $first20Lines; | |
//Если в $lines есть ещё хотя бы одна строка - проверим, возможно она сдержит слово Flag? Если так, то её нужно | |
//просто удалить, чтобы перейти к парсингу следующего блока на следующей итерации цикла | |
if (isset($lines[0])) { | |
if (strpos($lines[0], 'Flag:') !== false) { | |
array_shift($lines); | |
} | |
} | |
} | |
return $blocks; | |
} | |
$text = file_get_contents('php://stdin'); | |
$lines = array_map('trim', explode("\n", $text)); | |
$linesPerShipment = splitPerBlock($lines); | |
print count($linesPerShipment); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment