Hey guys I'm new here and was came here hoping to find an answer to my problem. I've never used priority queues before so I'm not sure I'm doing it right but here it goes...
I'm trying to create a huffman encoding / decoding program but I'm running into some issues. The encoding or decoding i'll tackle when i get there but i have a good grasp on that part anyways...
I need help turning my hashmap, which holds the character and the number of occurrences of it, and putting it into a priority queue. I have never used hashmaps or pqs before so i'm a little stumped.
import java.util.HashMap; import java.io.*; import java.util.Scanner; import java.util.Iterator; import java.lang.StringBuffer; import java.util.PriorityQueue; public class Huffman{ public static void main (String []args) throws Exception{ HashMap <Character, Integer> hm = new HashMap<Character, Integer>(); File file = new File("file.txt"); Scanner finput = new Scanner(file); StringBuffer text = new StringBuffer(""); PriorityQueue pq = new PriorityQueue(); while (finput.hasNext()){ String s = finput.next(); char [] chars = s.toCharArray(); for(int i=0; i < chars.length; i++){ char c = chars[i]; if (hm.containsKey(c)){ int freq = hm.get(c); hm.put(c, freq+1); } else{hm.put(c, 1);} } } System.out.println("Hashmap!"); System.out.println(hm); Iterator it = hm.keySet().iterator(); while(it.hasNext()){ pq.add(it.next()); } System.out.println("Priority Queue!"); while(pq.size() > 0){ System.out.println(pq.remove()); } } } class Node implements Comparable<Node> { private final char ch; private final int freq; private final Node left, right; Node(char ch, int freq, Node left, Node right) { this.ch = ch; this.freq = freq; this.left = left; this.right = right; } private boolean isLeaf() { assert (left == null && right == null) || (left != null && right != null); return (left == null && right == null); } public int compareTo(Node that) { return this.freq - that.freq; } }
It outputs...
Hashmap! {f=2, g=3, e=10, b=1, c=1, a=3, n=1, o=4, l=3, k=1, h=3, i=6, t=5, s=6, r=2, p=3, y=1, x=1} Priority Queue! a b c e f g h i k l n o p r s t x y
This is my text file... Though it doesn't matter what you use my program still isn't correct.
this is a text file go go gooberry please keep the spaces in this file
My priority queue should have the char with the highest frequency displayed first but it only shows chars anyways, how do i get it to show chars and frequencies also while putting them into the correct order?
Thanks guys!