grossvogel / huffman-coding-php

A toy implementation of a Huffman Coding in PHP
4 stars 4 forks source link

suggestion to simplify and perhaps optimize #3

Open ppKrauss opened 8 years ago

ppKrauss commented 8 years ago

This code use build-in functions,

function Huffman_DicEncode($symb2freq) {
    // from https://rosettacode.org/wiki/Huffman_coding#PHP
    $heap = new SplPriorityQueue;
    $heap->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
    foreach ($symb2freq as $sym => $wt)
        $heap->insert(array($sym => ''), -$wt);

    while ($heap->count() > 1) {
        $lo = $heap->extract();
        $hi = $heap->extract();
        foreach ($lo['data'] as &$x)
            $x = '0'.$x;
        foreach ($hi['data'] as &$x)
            $x = '1'.$x;
        $heap->insert($lo['data'] + $hi['data'],
                      $lo['priority'] + $hi['priority']);
    }
    $result = $heap->extract();
    return $result['data'];
}

function Huffman_compact2bin($txt,$base=36,$dic=NULL) {
    $s = '';
    $a = str_split($txt);
    $symb2freq = array_count_values($a);
    if ($dic===NULL)
        $dic = Huffman_DicEncode($symb2freq);
    foreach($a as $c) $s.=$dic[$c];
    return  $s;
}
grossvogel commented 8 years ago

Peter, Thanks for the suggestion. Since you seem very interested in this repository, I wanted to make sure you're clear on its origin and purpose.

I developed this code purely as an exercise, for fun, and I wouldn't attempt to use it in anything important. You're welcome to take it and run with it, but if you're building something with performance (or even correctness!) requirements, I'd definitely recommend using (or building) something else.