Skip to content

Instantly share code, notes, and snippets.

@PatrickG
Created February 7, 2011 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PatrickG/9020b83e6a13f51c24ed to your computer and use it in GitHub Desktop.
Save PatrickG/9020b83e6a13f51c24ed to your computer and use it in GitHub Desktop.
$numbers = array(13,81,80,79,78,77,76,19,40,41,42,43,44,45,48);
function compress_numbers(array $numbers)
{
$new = array(); $type = $cur = null;
foreach ($numbers as $number) {
if (!$cur) {
array_push($new, $number);
} elseif (!$type) {
if ($cur+1 == $number || $cur-1 == $number) {
$type = (($cur+1 == $number) ? '+' : '-');
array_pop($new); array_push($new, $cur . '-' . $number);
} else {
array_push($new, $number);
}
} elseif (('+' == $type && $cur+1 == $number) || ('-' == $type && $cur-1 == $number)) {
$tmp = array_pop($new);
array_push($new, substr($tmp, 0, strpos($tmp, '-')) . '-' . $number);
} else {
$type = null;
array_push($new, $number);
}
$cur = $number;
}
return $new;
}
function decompress_numbers(array $numbers)
{
$new = array();
foreach ($numbers as $number) {
if (is_numeric($number)) {
array_push($new, $number);
} else {
$tmp = explode('-', $number);
if ($tmp[0] < $tmp[1]) $tmp = array_keys(array_fill($tmp[0], $tmp[1]-$tmp[0]+1, null));
else $tmp = array_reverse(array_keys(array_fill($tmp[1], $tmp[0]-$tmp[1]+1, null)));
foreach ($tmp as $n) array_push($new, $n);
}
}
return $new;
}
var_dump($x = compress_numbers($numbers));
var_dump(decompress_numbers($x));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment