Skip to content

Instantly share code, notes, and snippets.

@pqr
Created September 3, 2014 12:55
Show Gist options
  • Save pqr/53accffe9d8ed336908a to your computer and use it in GitHub Desktop.
Save pqr/53accffe9d8ed336908a to your computer and use it in GitHub Desktop.
<?php
/* php скрипт в функциональном стиле (калька с Haskell) для статьи http://pqr7.wordpress.com/2014/09/03/haskell-vs-php/ */
ini_set('xdebug.max_nesting_level', 200000);
function parse($text) {
return splitPerBlocks(getLines($text));
}
function getLines($text) {
return array_map('trim', explode("\n", $text));
}
function splitPerBlocks(array $lines) {
return splitPerBlocksRecursiveFold([], $lines);
}
function splitPerBlocksRecursiveFold(array $blocks, array $lines) {
if (count($lines) < 20) {
return $blocks;
}
$linesWithoutHeaderAndFlag = dropFlagLine(dropHeaderLine($lines));
if (count($linesWithoutHeaderAndFlag) >= 20) {
$first20Lines = array_slice($linesWithoutHeaderAndFlag, 0, 20);
$otherLines = array_slice($linesWithoutHeaderAndFlag, 20);
$newFoundBlocks = $blocks;
$newFoundBlocks[] = $first20Lines;
return splitPerBlocksRecursiveFold($newFoundBlocks, $otherLines);
}
return $blocks;
}
function dropHeaderLine(array $lines) {
if (strpos(reset($lines), "Container No.") !== false) {
return array_slice($lines, 1);
}
return $lines;
}
function dropFlagLine(array $lines)
{
if (count($lines) <= 20) {
return $lines;
}
if (strpos($lines[20], "Flag:") !== false) {
return array_merge(array_slice($lines, 0, 20), array_slice($lines, 21));
}
return $lines;
}
$text = file_get_contents('php://stdin');
print count(parse($text));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment