0% found this document useful (0 votes)
15 views

Program

Uploaded by

Loganayagi P
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Program

Uploaded by

Loganayagi P
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

4. Implementation of Tree Traversal.

Aim:
To implement the tree traversal using Java Program.
Algorithm:
 int data: Represents the data or value stored in a tree node.
 TreeNode left: Represents the left child of the current node.
 TreeNode right: Represents the right child of the current node.
 public TreeNode(int data): Constructor to initialize a TreeNode with a
given data value. It sets the left and right children to null.
 TreeNode root: Represents the root of the binary tree.
 public BinaryTree(): Constructor to initialize an empty binary tree with a
null root.
 Performs in-order traversal starting from the given node. It recursively
traverses the left subtree, visits the current node, and then recursively
traverses the right subtree.
 Performs pre-order traversal starting from the given node. It visits the
current node, recursively traverses the left subtree, and then recursively
traverses the right subtree.
 Performs post-order traversal starting from the given node. It recursively
traverses the left subtree, recursively traverses the right subtree, and then
visits the current node.
 main method creates an instance of the BinaryTree class and initializes a
sample binary tree with numeric values.
 It then demonstrates in-order, pre-order, and post-order tree traversals by
calling the respective methods on the binary tree instance.

Program:
class TreeNode {
int data;
TreeNode left;
TreeNode right;

public TreeNode(int data) {


this.data = data;
this.left = null;
this.right = null;
}
}

class BinaryTree {
TreeNode root;

public BinaryTree() {
this.root = null;
}

// In-order traversal
public void inOrderTraversal(TreeNode node) {
if (node != null) {
inOrderTraversal(node.left);
System.out.print(node.data + “ “);
inOrderTraversal(node.right);
}
}

// Pre-order traversal
public void preOrderTraversal(TreeNode node) {
if (node != null) {
System.out.print(node.data + “ “);
preOrderTraversal(node.left);
preOrderTraversal(node.right);
}
}

// Post-order traversal
public void postOrderTraversal(TreeNode node) {
if (node != null) {
postOrderTraversal(node.left);
postOrderTraversal(node.right);
System.out.print(node.data + “ “);
}
}
}

public class TreeTraversalApp {


public static void main(String[] args) {
BinaryTree tree = new BinaryTree();

// Creating a sample binary tree


tree.root = new TreeNode(1);
tree.root.left = new TreeNode(2);
tree.root.right = new TreeNode(3);
tree.root.left.left = new TreeNode(4);
tree.root.left.right = new TreeNode(5);

System.out.println(“In-order traversal:”);
tree.inOrderTraversal(tree.root);

System.out.println(“\nPre-order traversal:”);
tree.preOrderTraversal(tree.root);

System.out.println(“\nPost-order traversal:”);
tree.postOrderTraversal(tree.root);
}
}

Output:
Result:
Hence the Tree traversal using java program was implemented Successfully.

10. Implementation of Kruskal Algorithm


Aim:
To Implement the Kruskal Algorithm using Java Program.

Algorithm:
 This class represents an edge in a graph, with three attributes: source,
destination, and weight.
 The constructor initializes the edge with the provided source, destination,
and weight.
 This class represents the Kruskal's algorithm implementation.
 It has private attributes vertices to store the number of vertices and edges to
store the edges of the graph using an Array List.
 The add Edge method allows adding edges to the graph by creating an
Edge object and adding it to the list of edges.
 he kruskalMST method is the core of Kruskal's algorithm.
 It sorts the edges based on their weights using Collections.sort and a
custom comparator.
 Initializes an empty list result to store the edges of the minimum spanning
tree and an array parent for union-find.
 A loop initializes each vertex as its own parent in the union-find data
structure.
 The algorithm iterates through the sorted edges until it finds enough edges
to form a minimum spanning tree.
 It checks if adding the next edge creates a cycle. If not, the edge is added to
the result, and the union-find data structure is updated.
 Finally, the minimum spanning tree is printed.
 The find method implements the find operation of the union-find algorithm.
It finds the root of the set to which a vertex belongs.
 The union method implements the union operation of the union-find
algorithm. It merges two sets by updating the parent pointers.
 The main method demonstrates the usage by creating an instance of the
KruskalAlgorithm class, adding edges, and calling the kruskalMST
method.
Program:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Edge {
int source, destination, weight;

public Edge(int source, int destination, int weight) {


this.source = source;
this.destination = destination;
this.weight = weight;
}
}

class KruskalAlgorithm {
private int vertices;
private List<Edge> edges;

public KruskalAlgorithm(int vertices) {


this.vertices = vertices;
this.edges = new ArrayList<>();
}

public void addEdge(int source, int destination, int weight) {


Edge edge = new Edge(source, destination, weight);
edges.add(edge);
}

public void kruskalMST() {


Collections.sort(edges, Comparator.comparingInt(edge -> edge.weight));

List<Edge> result = new ArrayList<>();


int[] parent = new int[vertices];

for (int i = 0; i < vertices; i++) {


parent[i] = i;
}

int index = 0;
int edgeCount = 0;

while (edgeCount < vertices - 1) {


Edge nextEdge = edges.get(index++);
int x = find(parent, nextEdge.source);
int y = find(parent, nextEdge.destination);

if (x != y) {
result.add(nextEdge);
union(parent, x, y);
edgeCount++;
}
}

System.out.println("Minimum Spanning Tree (Kruskal's Algorithm):");


for (Edge edge : result) {
System.out.println(edge.source + " - " + edge.destination + " : " +
edge.weight);
}
}

private int find(int[] parent, int vertex) {


if (parent[vertex] != vertex) {
parent[vertex] = find(parent, parent[vertex]);
}
return parent[vertex];
}

private void union(int[] parent, int x, int y) {


int rootX = find(parent, x);
int rootY = find(parent, y);
parent[rootX] = rootY;
}

public static void main(String[] args) {


KruskalAlgorithm graph = new KruskalAlgorithm(4);

// Adding edges with weights


graph.addEdge(0, 1, 10);
graph.addEdge(0, 2, 6);
graph.addEdge(0, 3, 5);
graph.addEdge(1, 3, 15);
graph.addEdge(2, 3, 4);

// Finding minimum spanning tree


graph.kruskalMST();
}
}

Output:

Result:
Hence the Kruskal Algorithm using Java program implemented Successfully.

11. You are supposed to build a Social Cop in your smart phone. Social Cop helps
people report crimes in the nearest police station in real time. Use K-d tree to
search for the police station nearest to the crime location before attempting to
report anything by constructing a 2 dimensional K-d tree from the location of all
the police stations in your city querying the K-d tree to find the nearest police to
the any given location in the city.

Aim:
The aim of building the "Social Cop" mobile application is to provide an efficient
and user-friendly platform for citizens to report crimes in real-time using Java
program.

Algorithm:
 Represents a node in the KD-tree with an array of coordinates (point) and
references to left and right child nodes.
 Initializes the KD-tree by calling the buildKDTree method with the
provided set of points (police station coordinates).
 The KD-tree is constructed recursively based on the median value of points
along alternating dimensions.
 Sorts the points based on the current dimension (axis) and calculates the
median index.
 Creates a new node with the median point and recursively builds the left
and right subtrees.
 Initiates the search for the nearest police station by calling the recursive
method findNearestPoliceStation.
 Takes a query point (crime location) and returns the coordinates of the
nearest police station.
 Traverses the KD-tree to find the nearest police station by comparing
distances along alternating dimensions.
 Decides whether to explore the next branch or the other branch based on
the query point's position relative to the current node.
 Determines whether it is necessary to explore the other branch based on the
distance to the best node found so far.
 Compares two nodes and returns the one closer to the query point.
 Calculates the Euclidean distance between two points.
 Creates an array of police station coordinates (policeStations) and a query
point representing a reported crime (crimeLocation).
 Builds a KD-tree using the KDTree class and finds the nearest police
station to the crime location.

Program:

import java.util.Comparator;

class Node {
int[] point;
Node left, right;

public Node(int[] point) {


this.point = point;
this.left = this.right = null;
}
}
class KDTree {
private Node root;

public KDTree(int[][] points) {


this.root = buildKDTree(points, 0, points.length - 1, 0);
}

private Node buildKDTree(int[][] points, int start, int end, int depth) {
if (start > end) {
return null;
}

int k = points[0].length; // Dimension of the points

// Sort points and build the tree recursively


int axis = depth % k;
Comparator<int[]> comparator = Comparator.comparingInt(p -> p[axis]);
java.util.Arrays.sort(points, start, end + 1, comparator);

int median = start + (end - start) / 2;


Node node = new Node(points[median]);

node.left = buildKDTree(points, start, median - 1, depth + 1);


node.right = buildKDTree(points, median + 1, end, depth + 1);

return node;
}

public int[] findNearestPoliceStation(int[] queryPoint) {


return findNearestPoliceStation(root, queryPoint, 0).point;
}

private Node findNearestPoliceStation(Node root, int[] queryPoint, int depth) {


if (root == null) {
return null;
}

int k = queryPoint.length;
int axis = depth % k;

Node nextBranch, otherBranch;


if (queryPoint[axis] < root.point[axis]) {
nextBranch = root.left;
otherBranch = root.right;
} else {
nextBranch = root.right;
otherBranch = root.left;
}

Node best = closerNode(root, findNearestPoliceStation(nextBranch,


queryPoint, depth + 1), queryPoint);

if (shouldCheckOtherBranch(root, queryPoint, best)) {


Node bestOther = findNearestPoliceStation(otherBranch, queryPoint,
depth + 1);
best = closerNode(root, bestOther, queryPoint);
}

return best;
}

private boolean shouldCheckOtherBranch(Node root, int[] queryPoint, Node


best) {
double distanceToBest = distance(root.point, best.point);
double axisDistance = Math.abs(root.point[queryPoint.length %
queryPoint.length] - queryPoint[queryPoint.length % queryPoint.length]);
return axisDistance < distanceToBest;
}

private Node closerNode(Node root, Node alternative, int[] queryPoint) {


if (alternative == null) {
return root;
}

double distanceRoot = distance(root.point, queryPoint);


double distanceAlternative = distance(alternative.point, queryPoint);

return distanceRoot < distanceAlternative ? root : alternative;


}

private double distance(int[] point1, int[] point2) {


double sum = 0;
for (int i = 0; i < point1.length; i++) {
sum += Math.pow(point1[i] - point2[i], 2);
}
return Math.sqrt(sum);
}
}

public class SocialCopApp {


public static void main(String[] args) {
// Coordinates of police stations (x, y)
int[][] policeStations = {
{1, 2},
{5, 8},
{10, 15},
{3, 6},
{12, 7}
};

// Location of a reported crime


int[] crimeLocation = {6, 10};

// Build KD-tree
KDTree kdTree = new KDTree(policeStations);

// Find nearest police station to the crime location


int[] nearestPoliceStation =
kdTree.findNearestPoliceStation(crimeLocation);

// Print the result


System.out.println("Nearest Police Station to the Crime Location:");
System.out.println("X: " + nearestPoliceStation[0] + ", Y: " +
nearestPoliceStation[1]);
}
}

Output:
Result:
Hence the java program for “Social Cop App” was implemented Successfully.

12. Implement Crossword puzzles as Constraint satisfaction problems

Aim:
To Implement Crossword puzzles as Constraint Satisfaction problems using Java
Program.

Algorithm:

 This statement imports the Arrays class from the java.util package. It is
used to initialize the crossword puzzle with empty spaces using
Arrays.fill().
 The CrosswordCSP class encapsulates the crossword puzzle CSP.
 puzzle: A 2D array (char[][]) representing the crossword puzzle.
 size: An integer representing the size (number of rows/columns) of the
crossword puzzle.
 Initializes the crossword puzzle with the specified size and calls the
initializePuzzle() method to set up the initial empty puzzle.
 Fills each row of the puzzle with empty spaces using Arrays.fill().
 Sets a word in the crossword puzzle at the specified position, either
horizontally or vertically.
 Creates an instance of CrosswordCSP with a size of 5.
 Sets words in the crossword puzzle using the setWord method.
 Displays the crossword puzzle using the displayPuzzle method.

Program:

import java.util.Arrays;
class CrosswordCSP {
private char[][] puzzle;
private int size;

public CrosswordCSP(int size) {


this.size = size;
this.puzzle = new char[size][size];
initializePuzzle();
}

private void initializePuzzle() {


for (char[] row : puzzle) {
Arrays.fill(row, ' '); // Initialize with empty spaces
}
}

public void setWord(String word, int row, int col, boolean isHorizontal) {
if (isHorizontal) {
for (int i = 0; i < word.length(); i++) {
puzzle[row][col + i] = word.charAt(i);
}
} else {
for (int i = 0; i < word.length(); i++) {
puzzle[row + i][col] = word.charAt(i);
}
}
}

public void displayPuzzle() {


for (char[] row : puzzle) {
for (char cell : row) {
System.out.print(cell + " ");
}
System.out.println();
}
}

public static void main(String[] args) {


CrosswordCSP crossword = new CrosswordCSP(5);

// Set words in the crossword


crossword.setWord("hello", 0, 0, false);
crossword.setWord("world", 0, 0, true);
crossword.setWord("java", 2, 1, true);
// Display the crossword puzzle
System.out.println("Crossword Puzzle:");
crossword.displayPuzzle();
}
}

Output:

Result:

Hence the Crossword puzzles as Constraint Satisfaction problems using Java


Program was implemented Successfully.
13. Develop an approximation algorithm for the problems like graph coloring,
vertex color Problem, Maximal flow, shortest path problems, Minimum
subsequence generation etc.

Aim:
Design and implement efficient approximation algorithms in Java for graph
coloring, maximal flow, shortest path, and minimum subsequence generation
problems, ensuring scalable and practical solutions.

Algorithm:

 vertices: Represents the number of vertices in the graph.


 Adjacency List: Represents the adjacency list of the graph using a list of
sets.
 Initializes the graph with a specified number of vertices.
 Creates an adjacency list with empty sets for each vertex.
 Adds an undirected edge between vertices u and v by updating the
adjacency list.
 Implements the greedy graph coloring algorithm.
 Initializes an array result to store the color assigned to each vertex.
 Initializes a boolean array availableColors to keep track of colors available
for each vertex.
 Iterates through each vertex and its neighbors.
 For each neighbor, marks its color as unavailable.
 Chooses the first available color for the current vertex.
 Resets the availability of colors for neighbors after color assignment.
 Creates a Graph object with 5 vertices.
 Adds edges to the graph.
 Invokes the greedyColoring method to perform graph coloring.
Program:

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Graph {
private int vertices;
private List<Set<Integer>> adjacencyList;

public Graph(int vertices) {


this.vertices = vertices;
this.adjacencyList = new ArrayList<>(vertices);
for (int i = 0; i < vertices; i++) {
adjacencyList.add(new HashSet<>());
}
}

public void addEdge(int u, int v) {


adjacencyList.get(u).add(v);
adjacencyList.get(v).add(u);
}

public void greedyColoring() {


int[] result = new int[vertices];
boolean[] availableColors = new boolean[vertices];
result[0] = 0;

for (int i = 1; i < vertices; i++) {


result[i] = -1; // Initialize color of current vertex as unassigned
}

for (int u = 1; u < vertices; u++) {


for (int v : adjacencyList.get(u)) {
if (result[v] != -1) {
availableColors[result[v]] = true;
}
}
int color;
for (color = 0; color < vertices; color++) {
if (!availableColors[color]) {
break;
}
}

result[u] = color;

// Reset the values back to false for the next iteration


for (int v : adjacencyList.get(u)) {
if (result[v] != -1) {
availableColors[result[v]] = false;
}
}
}

// Print the coloring result


System.out.println("Vertex \tColor");
for (int i = 0; i < vertices; i++) {
System.out.println(i + " \t" + result[i]);
}
}
}

public class GraphColoringApp {


public static void main(String[] args) {
Graph graph = new Graph(5);
graph.addEdge(0, 1);
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.addEdge(1, 3);
graph.addEdge(2, 3);
graph.addEdge(3, 4);

System.out.println("Graph Coloring using Greedy Algorithm:");


graph.greedyColoring();
}
}

Output:
Result:
Hence Graph Coloring using Greedy Algorithm was implemented successfully.

Aim:
To implement the Shortest Path Algorithm using JAVA program.

Algorithm:

1. Assign to every node a distance value. Set it to zero for our initial node and to infinity
for all other nodes.
2. Mark all nodes as unvisited. Set initial node as current.
3. For current node, consider all its unvisited neighbours and calculate their distance (from
the initial node). For example, if current node (A) has distance of 6, and an edge connecting
it with another node (B) is 2, the distance to B through A will be 6+2=8. If this distance is
less than the previously recorded distance (infinity in the beginning, zero for the initial
node), overwrite the distance.
4. When we are done considering all neighbours of the current node, mark it as visited. A
visited node will not be checked ever again; its distance recorded now is final and
minimal.
5. Set the unvisited node with the smallest distance (from the initial node) as the next
"current node" and continue from step 3.
6. When all nodes are visited, algorithm ends.

Program:
import java.util.HashSet;
import java.util.InputMismatchException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Dijkstras_Shortest_Path
{
private int distances[];
private Set<Integer> settled;
private Set<Integer> unsettled;
private int number_of_nodes;
private int adjacencyMatrix[][];
public Dijkstras_Shortest_Path(int number_of_nodes)
{
this.number_of_nodes = number_of_nodes;
distances = new int[number_of_nodes + 1];
settled = new HashSet<Integer>();
unsettled = new HashSet<Integer>();
adjacencyMatrix = new int[number_of_nodes + 1][number_of_nodes + 1];
}
public void dijkstra_algorithm(int adjacency_matrix[][], int source)
{
int evaluationNode;
for (int i = 1; i <= number_of_nodes; i++)
for (int j = 1; j <= number_of_nodes; j++)
adjacencyMatrix[i][j] = adjacency_matrix[i][j];

for (int i = 1; i <= number_of_nodes; i++)


{
distances[i] = Integer.MAX_VALUE;
}
unsettled.add(source);
distances[source] = 0;
while (!unsettled.isEmpty())
{
evaluationNode = getNodeWithMinimumDistanceFromUnsettled();
unsettled.remove(evaluationNode);
settled.add(evaluationNode);
evaluateNeighbours(evaluationNode);
}}
private int getNodeWithMinimumDistanceFromUnsettled()
{
int min;
int node = 0;
Iterator<Integer> iterator = unsettled.iterator();
node = iterator.next();
min = distances[node];
for (int i = 1; i <= distances.length; i++)
{
if (unsettled.contains(i))
{
if (distances[i] <= min)
{
min = distances[i];
node = i;
}}}
return node;
}
private void evaluateNeighbours(int evaluationNode)
{
int edgeDistance = -1;
int newDistance = -1;
for (int destinationNode = 1; destinationNode <= number_of_nodes; destinationNode++)
{
if (!settled.contains(destinationNode))
{
if (adjacencyMatrix[evaluationNode][destinationNode] != Integer.MAX_VALUE)
{
edgeDistance = adjacencyMatrix[evaluationNode][destinationNode];
newDistance = distances[evaluationNode] + edgeDistance;
if (newDistance < distances[destinationNode])
{
distances[destinationNode] = newDistance;
}
unsettled.add(destinationNode);
}}}}
public static void main(String... arg)
{
int adjacency_matrix[][];
int number_of_vertices;
int source = 0, destination = 0;
Scanner scan = new Scanner(System.in);
try
{
System.out.println("Enter the number of vertices");
number_of_vertices = scan.nextInt();
adjacency_matrix = new int[number_of_vertices + 1][number_of_vertices + 1];
System.out.println("Enter the Weighted Matrix for the graph");
for (int i = 1; i <= number_of_vertices; i++)
{
for (int j = 1; j <= number_of_vertices; j++)
{
adjacency_matrix[i][j] = scan.nextInt();
if (i == j)
{
adjacency_matrix[i][j] = 0;
continue;
}
if (adjacency_matrix[i][j] == 0)
{
adjacency_matrix[i][j] = Integer.MAX_VALUE;
}}}
System.out.println("Enter the source ");
source = scan.nextInt();
System.out.println("Enter the destination ");
destination = scan.nextInt();
Dijkstras_Shortest_Path dijkstrasAlgorithm = new Dijkstras_Shortest_Path(
number_of_vertices);
dijkstrasAlgorithm.dijkstra_algorithm(adjacency_matrix, source);
System.out.println("The Shorted Path from " + source + " to " + destination + " is: ");
for (int i = 1; i <= dijkstrasAlgorithm.distances.length - 1; i++)
{
if (i == destination)
System.out.println(source + " to " + i + " is " + dijkstrasAlgorithm.distances[i]);
} } catch (InputMismatchException inputMismatch)
{
System.out.println("Wrong Input Format");
}
scan.close();
}}
Output:

Result:
Thus the implementation of the Shortest Path Algorithm using JAVA program was
executed successfully.
Ex no:
Date:
10. Implementation of Matrix Chain Multiplication

Aim:
To implement the Matrix Chain Multiplication using JAVA program.

Algorithm:

1. Take the sequence of matrices and separate it into two subsequences.


2. Find the minimum cost of multiplying out each subsequence.
3. Add these costs together, and add in the cost of multiplying the two result matrices.
4. Do this for each possible position at which the sequence of matrices can be split,
and take the minimum over all of them

Program:
import java.io.*;
import java.util.*;
import java.lang.StringBuffer;
public class MCM
{
public int N[][];
public int d[];
public int SIZE = 5;
public static void main( String [ ] args ) throws Exception
{
MCM mcm = new MCM();
mcm.init();
int result = mcm.minMCM();
System.out.println("result = " + result);
}
public void init()
{
N = new int[SIZE][SIZE];
d = new int[SIZE+1];
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if (i == j)
N[i][j] = 0;
else
N[i][j] = 999;
}}
d[0] = 2;
d[1] = 4;
d[2] = 2;
d[3] = 3;
d[4] = 1;
d[5] = 4;
}
public int minMCM()
{
for (int i = 1; i <= SIZE; i++)
{
for (int j = 0; j <= SIZE-i; j++)
{
for (int k = j; k < j+i-1; k++)
{
if (N[j][j+i-1] > N[j][k]+N[k+1][j+i-1] + d[j]*d[k+1]*d[i+j])
{
N[j][j+i-1] = N[j][k]+N[k+1][j+i-1] + d[j]*d[k+1]*d[i+j];
}}}}
System.out.println("N = ");
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
System.out.print(N[i][j] + "\t");
}
System.out.println();
}
System.out.println();
return N[0][SIZE-1];
}}

Output:
Result:
Thus the implementation of the Matrix Chain Multiplication using JAVA program was
executed successfully.
Ex no:
Date:

11. Activity Selection and Huffman Coding Implementation

Aim:
To implement the Activity Selection and Huffman Coding using JAVA program.

Algorithm:

1. Create a leaf node for each unique character and build a min heap of all leaf nodes
(Min Heap is used as a priority queue. The value of frequency field is used to
compare two nodes in min heap. Initially, the least frequent character is at root)
2. Extract two nodes with the minimum frequency from the min heap.
3. Create a new internal node with frequency equal to the sum of the two nodes
frequencies. Make the first extracted node as its left child and the other extracted
node as its right child. Add this node to the min heap.
4. Repeat steps #2 and #3 until the heap contains only one node. The remaining
node is the root node and the tree is complete.
Program:
import java.util.*;
abstract class HuffmanTree implements Comparable<HuffmanTree>
{
public final int frequency;
public HuffmanTree(int freq)
{
frequency = freq;
}
public int compareTo(HuffmanTree tree)
{
return frequency - tree.frequency;
}}
class HuffmanLeaf extends HuffmanTree
{
public final char value;
public HuffmanLeaf(int freq, char val)
{
super(freq)
; value =
val;
}}
class HuffmanNode extends HuffmanTree
{
public final HuffmanTree left, right;
public HuffmanNode(HuffmanTree l, HuffmanTree r)
{
super(l.frequency + r.frequency);
left = l;
right = r;
}}
public class HuffmanCode
{
public static HuffmanTree buildTree(int[] charFreqs)
{
PriorityQueue<HuffmanTree> trees = new
PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++)
if (charFreqs[i] > 0)
trees.offer(new HuffmanLeaf(charFreqs[i], (char)i));
assert trees.size() > 0;
while (trees.size() > 1)
{
HuffmanTree a = trees.poll();
HuffmanTree b = trees.poll();
trees.offer(new HuffmanNode(a, b));
}
return trees.poll();
}
public static void printCodes(HuffmanTree tree, StringBuffer prefix)
{
assert tree != null;
if (tree instanceof HuffmanLeaf)
{
HuffmanLeaf leaf = (HuffmanLeaf)tree;
System.out.println(leaf.value + "\t" + leaf.frequency + "\t" +
prefix);
}
else if (tree instanceof HuffmanNode)
{
HuffmanNode node = (HuffmanNode)tree;
prefix.append('0');
printCodes(node.left, prefix);
prefix.deleteCharAt(prefix.length()-
1); prefix.append('1');
printCodes(node.right, prefix);
prefix.deleteCharAt(prefix.length()-
1);
}}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("\nEnter the
String:"); String test=sc.nextLine();
int[] charFreqs = new
int[256]; for (char c :
test.toCharArray())
charFreqs[c]++;
HuffmanTree tree = buildTree(charFreqs);
System.out.println("SYMBOL\tWEIGHT\tHUFFMAN
CODE"); printCodes(tree, new StringBuffer());
}}

Output:
Result:
Thus the implementation of the Activity Selection and Huffman Coding using JAVA
program was executed successfully.

You might also like