This shows you the differences between two versions of the page.
|
huffman [2009/03/23 16:05] admin created |
huffman [2009/03/23 16:17] (current) admin Added shared dictionary |
||
|---|---|---|---|
| Line 36: | Line 36: | ||
| </code> | </code> | ||
| - | ===== Reusing Huffman Trees ===== | + | ===== Re-using Huffman Trees ===== |
| - | todo | + | In the above examples, the Huffman tree (also called the "dictionary") which maps values (or characters) to bits is embedded in the compressed data. Sometimes, however, you may want to re-use the dictionary for more than one item to compress. This is how it works: |
| + | |||
| + | <code php> | ||
| + | $original1 = "This is the first text we want to compress."; | ||
| + | $original2 = "This is the second text we want to compress."; | ||
| + | $huffman = new Huffman(); | ||
| + | $huffman->buildTree($original1.$original2); | ||
| + | $dictionary = $huffman->getDictionary(); | ||
| + | $compressed1 = $huffman->compressData($original1,false); | ||
| + | $compressed2 = $huffman->compressData($original2,false); | ||
| + | /* ... */ | ||
| + | $huffman2 = new Huffman($dictionary); | ||
| + | echo $huffman->decompressData($compressed1,false)."\n"; | ||
| + | echo $huffman->decompressData($compressed2,false); | ||
| + | // Should output both original strings. | ||
| + | </code> | ||
| + | |||
| + | This works exactly the same with arrays but you'll have to let the functions know that you want arrays with "true" instead of "false" in the functions above. See also documentation in source code. | ||
| + | |||
| + | And of course, this also works in JavaScript. | ||