Last active
February 11, 2023 14:46
-
-
Save azazar/ced59e0e398eb15905ebe3bf5ada89ed to your computer and use it in GitHub Desktop.
Routines for compressed serialization and deserialization of integer sets
This file contains hidden or 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 | |
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