Created
February 23, 2011 20:22
-
-
Save DracoBlue/841110 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 | |
/** | |
* Reconstruct an array, for small task at: http://www.phpgangsta.de/kleine-aufgabe-ein-array-umbauen | |
* Contribution by DracoBlue | |
*/ | |
function compress($in) | |
{ | |
$in_length = count($in); | |
$start = $last = $current = $in[0]; | |
$direction = 0; | |
$out = array(); | |
$i = 1; | |
while ($i < $in_length) | |
{ | |
$last = $current; | |
$current = $in[$i++]; | |
if ($last - 1 === $current && $direction >= 0) | |
{ | |
$direction = 1; | |
continue; | |
} | |
elseif ($last + 1 === $current && $direction <= 0) | |
{ | |
$direction = -1; | |
continue; | |
} | |
elseif ($start !== $last) | |
{ | |
$out[] = $start . '-' . $last; | |
} | |
else | |
{ | |
$out[] = $start; | |
} | |
$direction = 0; | |
$start = $current; | |
} | |
$last = $current; | |
if ($start !== $last) | |
{ | |
$out[] = $start . '-' . $last; | |
} | |
else | |
{ | |
$out[] = $start; | |
} | |
return $out; | |
} | |
function decompress($in) | |
{ | |
$out = array(); | |
foreach ($in as $current) | |
{ | |
if (is_string($current)) | |
{ | |
list($start, $end) = explode('-', $current); | |
foreach (range($start, $end) as $value) | |
{ | |
$out[] = $value; | |
} | |
} | |
else | |
{ | |
$out[] = $current; | |
} | |
} | |
return $out; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment