Skip to content

Instantly share code, notes, and snippets.

@azazar
Last active February 11, 2023 14:46
Show Gist options
  • Save azazar/ced59e0e398eb15905ebe3bf5ada89ed to your computer and use it in GitHub Desktop.
Save azazar/ced59e0e398eb15905ebe3bf5ada89ed to your computer and use it in GitHub Desktop.
Routines for compressed serialization and deserialization of integer sets
<?php
function compress_int_set($arr) {
if (count($arr) == 0) {
return '';
}
sort($arr);
$prev = $arr[0];
$arr[0] = base_convert($arr[0], 10, 36);
for($i = 1; $i < count($arr); $i++) {
$cur = $arr[$i];
$arr[$i] = base_convert($cur - $prev, 10, 36);
$prev = $cur;
}
return implode(',', $arr);
}
function decompress_int_set($str) {
if (empty($str)) {
return [];
}
$arr = explode(',', $str);
$arr[0] = intval(base_convert($arr[0], 36, 10));
for($i = 1; $i < count($arr); $i++) {
$arr[$i] = $arr[$i - 1] + intval(base_convert($arr[$i], 36, 10));
}
return $arr;
}
$src = [1000,1030,1060,1090,1111,1140,2100];
$comp = compress_int_set($src); // it becomes "rs,u,u,u,l,t,qo"
$dec = decompress_int_set($comp);
echo json_encode([$src,$comp,$dec]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment