Huffman PHP Decoding Algorithm

I recently applied for a job and I was sent a hacker exam with a few questions. One of them was a Huffman decoding algorithm. There is a similar problem here that explains formatting much better than I can.

The actual task was to take two arguments and return the decoded string.

The first argument is the codes, which are a string array, for example:

[
    "a      00",
    "b      101",
    "c      0111",
    "[newline]      1001"
]

It's like: a single character, two tabs, a huffman code.

A new line was indicated as being in this format due to how the hacker rank was set.

The second argument is a string for decoding using codes. For instance:

101000111 = bac

This is my decision:

function decode($codes, $encoded) {
    $returnString = '';
    $codeArray = array();

    foreach($codes as $code) {
        sscanf($code, "%s\t\t%s", $letter, $code);
        if ($letter == "[newline]")
            $letter = "\n";
        $codeArray[$code] = $letter;
    }
    print_r($codeArray);

    $numbers = str_split($encoded);
    $searchCode = '';
    foreach ($numbers as $number) {
        $searchCode .= $number;
        if (isset($codeArray[$searchCode])) {
            $returnString .= $codeArray[$searchCode];
            $searchCode = '';
        }
    }

    return $returnString;
}

, , , .

, , , , substr , , . , , , .

, , .

, , - , . , , , .

+4
1

. , .. , , , . , .

. -, , 010, 0110, 1000 11 . , .

, , . , $searchCode . , . , . , ?

, , , . , , ? , . , [newline]? , , , , . ? , , .

+1

Source: https://habr.com/ru/post/1686115/


All Articles