Wednesday, 15 May 2013

arrays - Creating a Huffman Tree in PHP -



arrays - Creating a Huffman Tree in PHP -

i trying create huffman tree using php.

this have:

<!doctype html> <html> <body> <?php $extract = 'lorem ipsum dolor sit down amet, consectetur adipiscing elit. suspendisse elementum imperdiet aliquet. duis non molestie orci. ut eget nibh nec augue ultricies porttitor.'; $characters = count_chars($extract, 1); asort($characters); foreach($characters $character => $occurrence) { echo 'there'; if($occurrence > 1) { echo ' ' . $occurrence . ' occurrences of '; } else { echo ' '. $occurrence . ' occurrence of '; } echo '"<strong>' . chr($character) . '</strong>" in extract.<br />'; $characterfreq[chr($character)] = $occurrence; } print_r($characterfreq); ?> </body> </html>

which outputs:

there 1 occurrence of "s" in extract. there 1 occurrence of "u" in extract. there 1 occurrence of "h" in extract. there 1 occurrence of "l" in extract. there 1 occurrence of "d" in extract. there 1 occurrence of "," in extract. there 1 occurrence of "q" in extract. there 1 occurrence of "b" in extract. there 3 occurrences of "g" in extract. there 4 occurrences of "a" in extract. there 4 occurrences of "." in extract. there 4 occurrences of "d" in extract. there 5 occurrences of "p" in extract. there 6 occurrences of "c" in extract. there 6 occurrences of "l" in extract. there 7 occurrences of "m" in extract. there 8 occurrences of "n" in extract. there 8 occurrences of "r" in extract. there 9 occurrences of "u" in extract. there 9 occurrences of "o" in extract. there 10 occurrences of "s" in extract. there 15 occurrences of "t" in extract. there 17 occurrences of "i" in extract. there 20 occurrences of "e" in extract. there 22 occurrences of " " in extract. array ( [s] => 1 [u] => 1 [h] => 1 [l] => 1 [d] => 1 [,] => 1 [q] => 1 [b] => 1 [g] => 3 [a] => 4 [.] => 4 [d] => 4 [p] => 5 [c] => 6 [l] => 6 [m] => 7 [n] => 8 [r] => 8 [u] => 9 [o] => 9 [s] => 10 [t] => 15 [i] => 17 [e] => 20 [ ] => 22 )

i have been using mixtures of array_slice(), array_splice() , array_unshift() having problem recursion.

ideally, leaves , branches denoted array indices 0 & 1.

any ideas on how create huffman tree in multidimensional array form appreciated.

php arrays recursion tree huffman-coding

No comments:

Post a Comment