Skip to content

Instantly share code, notes, and snippets.

@yetimdasturchi
Created March 3, 2024 02:53
Show Gist options
  • Save yetimdasturchi/ad132f74c0c94f997b1d93f041033715 to your computer and use it in GitHub Desktop.
Save yetimdasturchi/ad132f74c0c94f997b1d93f041033715 to your computer and use it in GitHub Desktop.
Huffman coding in php
<?php
function huffmannEncode($string) {
$originalString = $string;
$occurences = array();
while (isset($string[0])) {
$occurences[] = array(substr_count($string, $string[0]), $string[0]);
$string = str_replace($string[0], '', $string);
}
sort($occurences);
while (count($occurences) > 1) {
$row1 = array_shift($occurences);
$row2 = array_shift($occurences);
$occurences[] = array($row1[0] + $row2[0], array($row1, $row2));
sort($occurences);
}
$dictionary = [];
fillDictionary($dictionary, is_array($occurences[0][1]) ? $occurences[0][1] : $occurences);
$encoded = '';
for($i = 0; $i < strlen($originalString); $i++) {
$encoded .= $dictionary[$originalString[$i]];
}
return [
'code' => $encoded,
'dictionary' => $dictionary
];
}
function fillDictionary(&$dictionary, $data, $value = '') {
if (!is_array($data[0][1])) {
$dictionary[$data[0][1]] = $value.'0';
} else {
fillDictionary($dictionary, $data[0][1], $value.'0');
}
if (isset($data[1])) {
if (!is_array($data[1][1])) {
$dictionary[$data[1][1]] = $value.'1';
} else {
fillDictionary($dictionary, $data[1][1], $value.'1');
}
}
}
function huffmannDecode($encodedData, $dictionary) {
$decoded = '';
$currentCode = '';
for ($i = 0; $i < strlen($encodedData); $i++) {
$currentCode .= $encodedData[$i];
foreach ($dictionary as $char => $code) {
if ($code === $currentCode) {
$decoded .= $char;
$currentCode = '';
break;
}
}
}
return $decoded;
}
$input = "salom dunyo";
echo "Input: {$input}\n";
$encodedData = huffmannEncode( $input );
echo "Encoded: {$encodedData['code']}\n";
$decodedData = huffmannDecode( $encodedData['code'], $encodedData['dictionary'] );
echo "Decoded: {$decodedData}\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment