Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
64
Task/LZW-compression/PHP/lzw-compression.php
Normal file
64
Task/LZW-compression/PHP/lzw-compression.php
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
class LZW
|
||||
{
|
||||
function compress($unc) {
|
||||
$i;$c;$wc;
|
||||
$w = "";
|
||||
$dictionary = array();
|
||||
$result = array();
|
||||
$dictSize = 256;
|
||||
for ($i = 0; $i < 256; $i += 1) {
|
||||
$dictionary[chr($i)] = $i;
|
||||
}
|
||||
for ($i = 0; $i < strlen($unc); $i++) {
|
||||
$c = $unc[$i];
|
||||
$wc = $w.$c;
|
||||
if (array_key_exists($w.$c, $dictionary)) {
|
||||
$w = $w.$c;
|
||||
} else {
|
||||
array_push($result,$dictionary[$w]);
|
||||
$dictionary[$wc] = $dictSize++;
|
||||
$w = (string)$c;
|
||||
}
|
||||
}
|
||||
if ($w !== "") {
|
||||
array_push($result,$dictionary[$w]);
|
||||
}
|
||||
return implode(",",$result);
|
||||
}
|
||||
|
||||
function decompress($com) {
|
||||
$com = explode(",",$com);
|
||||
$i;$w;$k;$result;
|
||||
$dictionary = array();
|
||||
$entry = "";
|
||||
$dictSize = 256;
|
||||
for ($i = 0; $i < 256; $i++) {
|
||||
$dictionary[$i] = chr($i);
|
||||
}
|
||||
$w = chr($com[0]);
|
||||
$result = $w;
|
||||
for ($i = 1; $i < count($com);$i++) {
|
||||
$k = $com[$i];
|
||||
if (isset($dictionary[$k])) {
|
||||
$entry = $dictionary[$k];
|
||||
} else {
|
||||
if ($k === $dictSize) {
|
||||
$entry = $w.$w[0];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
$result .= $entry;
|
||||
$dictionary[$dictSize++] = $w . $entry[0];
|
||||
$w = $entry;
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
//How to use
|
||||
$str = 'TOBEORNOTTOBEORTOBEORNOT';
|
||||
$lzw = new LZW();
|
||||
$com = $lzw->compress($str);
|
||||
$dec = $lzw->decompress($com);
|
||||
echo $com . "<br>" . $dec;
|
||||
Loading…
Add table
Add a link
Reference in a new issue