Skip to content

Instantly share code, notes, and snippets.

@pce
Created December 11, 2011 13:52
Show Gist options
  • Save pce/1460718 to your computer and use it in GitHub Desktop.
Save pce/1460718 to your computer and use it in GitHub Desktop.
ascii map text-format generator, asserts a test when invoked from cli
<?php
function ascii_lexan($s)
{
$tokens = array();
$strlen = strlen($s);
for ($i = 0;$i < $strlen; $i++) {
$tokens []= ord($s[$i]);
}
return $tokens;
}
function ascii_parse($tokens)
{
$count = 1;
$tokenStr = '';
$prevToken = '';
$isFirstToken = true;
$lastIndex = count($tokens) -1;
foreach ($tokens as $index => $token) {
// printf("<%s, %s [%s]>\n", $count, $token, $prevToken);
if ($isFirstToken) {
$prevToken = $token;
$isFirstToken = false;
continue;
}
if ($prevToken != $token) {
$tokenStr .= $count.':'.$prevToken.'|';
$prevToken = $token;
$count = 1;
} else {
$count++;
}
if ($index == $lastIndex) {
$tokenStr .= $count.':'.$prevToken;
}
}
return $tokenStr;
}
function asciimap_create($s)
{
$tokens = ascii_lexan($s);
return ascii_parse($tokens);
}
function asciimap_read($s)
{
$out = '';
$instructions = explode('|', $s);
foreach ($instructions as $index => $instruction) {
$_ = explode(':', $instruction);
$count = $_[0];
$ascii = $_[1];
for ($i = 0;$i < $count; $i++)
$out .= chr($ascii);
}
return $out;
}
// Test wenn Skript direkt aufgerufen wird:
if (count(debug_backtrace()) == 0) {
$ascii = <<<EOF
O---O
/ \ / \
O---O---O
\ / \ /
O---O
EOF;
$s = asciimap_create($ascii);
assert('asciimap_read($s)==$ascii2');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment