MCPcopy Create free account
hub / github.com/Ayush7614/Daily-Coding-DS-ALGO-Practice / GFG

Class GFG

Gfg/Java/Huffman Encoding.java:3–76  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.lang.*;
2import java.io.*;
3class GFG
4 {
5 public static void main (String[] args)
6 {
7 //code
8 Scanner s=new Scanner(System.in);
9 int T=s.nextInt();
10 for(int i=0;i<T;i++)
11 {
12 String str=s.next();
13 int[] arr=new int[str.length()];
14 for(int j=0;j<arr.length;j++)
15 {
16 arr[j]=s.nextInt();
17 }
18 encode(str,arr);
19 System.out.println();
20 }
21 }
22
23 public static void encode(String str,int[] arr)
24 {
25 PriorityQueue<Node> queue=new PriorityQueue<>(new Comparator<Node>()
26 {
27 @Override
28 public int compare(Node n1,Node n2)
29 {
30 if(n1.freq==n2.freq)
31 return 1;
32 return n1.freq-n2.freq;
33 }
34 }
35 );
36 for(int i=0;i<str.length();i++)
37 {
38 Node node=new Node(""+str.charAt(i),arr[i],null,null);
39 queue.add(node);
40 }
41 while(queue.size()>1)
42 {
43 Node node1=queue.remove();
44 Node node2=queue.remove();
45 Node node=new Node(node1.name+node2.name,node1.freq+node2.freq,node1,node2);
46 queue.add(node);
47 }
48 huffmanencode(queue.peek(),"");
49 }
50
51 public static void huffmanencode(Node root,String res)
52 {
53 if(root.left==null&&root.right==null)
54 {
55 System.out.print(res+" ");
56 return;
57 }
58 huffmanencode(root.left,res+"0");
59 huffmanencode(root.right,res+"1");
60 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected