Permalink
Browse files

creating a huffman code tree

  • Loading branch information...
1 parent 4042f24 commit c79440c699a468a7ca3229ed572a1da92643e077 nick orton committed Jun 3, 2012
Showing with 42 additions and 0 deletions.
  1. +30 −0 src/techne/algos/huffman.clj
  2. +12 −0 test/techne/algos/huffman_test.clj
@@ -0,0 +1,30 @@
+(ns techne.algos.huffman
+ (:import [java.util PriorityQueue]))
+
+(defstruct node :freq :value :left :right)
+
+(def node-comparator
+ (comparator
+ #(< (:freq %1) (:freq %2))))
+
+(defn priority-queue []
+ (PriorityQueue. 10 node-comparator))
+
+(defn build-queue [frequency-map]
+ (let [queue (priority-queue)]
+ (doseq [keyval frequency-map]
+ (.add queue (struct node (second keyval) (first keyval))))
+ queue))
+
+
+(defn build-huffman-code-tree [frequency-map]
+ (loop [queue (build-queue frequency-map)]
+ (if (= 1 (.size queue))
+ (.poll queue)
+ (let [left (.poll queue)
+ right (.poll queue)
+ freq (+ (:freq left) (:freq right))
+ n (struct node freq nil left right)]
+ (.add queue n)
+ (recur queue)))))
+
@@ -0,0 +1,12 @@
+(ns techne.algos.huffman-test
+ (use [techne.algos.huffman]
+ [clojure.test]))
+
+(deftest test-build-code-tree
+ (let [freq-map {\a 45 \b 13 \c 12 \d 16 \e 9 \f 5}
+ tree (build-huffman-code-tree freq-map)]
+ (is (= \a (:value (:left tree))))
+ (is (= \d (:value (:right (:right (:right tree))))))))
+
+;TODO convert tree into codes
+

0 comments on commit c79440c

Please sign in to comment.