Posts

Showing posts from May, 2025

Counting connected components in a graph

               It is a basic problem in graph. A graph contains nodes and edges. Nodes can be a vertices and edges connecting the nodes. Here, connected component means every node is reached from any other node. The traversal of node may be DFS(Depth First Search) or BFS(Breadth First Search) according to it. Let us count the counted component in graph. Program implementation: This program gets the number of nodes and edges as input. It uses DFS(Depth first Search) to traverse the nodes. ‘g_dfs()’ used to traverse the graph. It gets the nodes, adjacent list and a Boolean value ‘g_visited’ to perform the traversal. It sets the ‘g_visited’ value when it reaches the node. ‘countIt()’ -This function gets the number of nodes and edges as input. It checks the ‘g_visited’   value for entire graph. Find the edges visited. Finally, gives you the count. ‘main()’ – this function assigns the input value as number of nodes and edges. It calls the ...

Java Program to find Subsets of a Set

               Set has a collections of elements. Sub set contains the combinations of elements. It can be done by bit manipulation or recursion. Java implementation: It starts with including the built in packages java.util.ArrayList and java.util.List. A public class is created with main (). A integer array is assigned with elements. A subset is developed as list. Let us call the findSubset() function to get the subsets. ‘findSubset()’ – This function creates the subsets of the given set. Finally, it prints the sub sets. Technical information: Class name: SubsetFinderEg Variables: set1 as integer array. subset1 as integer list. Index as integer ‘all_Subsets, ‘new_Subset’,’more_Subsets’ as array list. S_item as integer. Member function: findSubset(). Program: //include the built-in packages. import java.util.ArrayList; import java.util.List; //class creation with main() class public class SubsetFinderEg ...

Huffman Encoding implementation in java

 Huffman Encoding is an algorithm which provides compression of data. The encoding deals with the character frequencies to reduce the size of data. Java implementation:               This process starts with finding the frequency of each character. Next, it creates the Huffman Tree by the use of a   priority   queue. Finally, it develops the binary codes for each character. Program: import java.util.PriorityQueue; import java.util.HashMap; import java.util.Map; // let us create the class with character with its frequency class HuffmanNode implements Comparable<HuffmanNode> {     char h_char;     int h_freq;     HuffmanNode h_left, h_right;     HuffmanNode(char h_char, int h_freq) {         this.h_char = h_char;         this.h_freq = h_freq; ...

Implementing a Trie for word search in Java

What is a Trie?               It is a data structure looks like a tree. Usually, it stores the data and retrieves it accordingly. It is similar to prefix tree. Usage: prefix lookup, insert a data and fast search. Applications: spell checking,dictionary and autocomplete. Program implementation:               The implementation starts with including the built-in package java.util. Classes included in this program: TrieNodeEg :it creates the node and its elements. TrieEg : This develops the root node and its value. It includes three member functions. TrieSample:It is in main() function. it creates the object and calls the member functions to execute to get the output. Member variables: Children -it is a hash map object. isEOF – it is a Boolean value for store the EOF value. t_root -root elements t_node – node element wrd – input to ...

N-Queen Problem in java

              It is a backtracking method to solve the problem. Basically, it is a NxN chessboard which has N queens. It should not attack each other. Java Implementation: Create a public class with main() function. Add four functions solveNQueensPbm(),backtracking(),isItSafe(),printItBoard(). solveNQueensPbm() – create a character array. add the data. Call the backtracking() function. backtracking() – it checks the row with n value and call the printItBoard() function. use for loop to perform backtracking(). printItBoard() -It prints the board and queens value. ‘main()’- it creates the value for n and calls the solveNQueensPbm() to get the output. Program: import java.util.Arrays; public class NQueensEg {     public static void solveNQueensPbm(int n) {         char[][] board1 = new char[n][n];         for (char[] q_row : board1) Arrays.fill(q...

How to implement the java Program to generate permutation of string?

 What is permutation?               It is a specific order of arrangement in alphabets or numbers. Generally, it arranges the set of elements. In terms of mathematics, it uses factorial concept. For eg:   ‘XY’ – this is the input string. The permutations are { ‘XY,’YX’} Program implementation: Class: permutationString Member functions: ‘generateIt()’ ‘main()’ Member variables: ‘str1’ ,’perm1’ , ‘s_remaining’, ‘sample’ -String variables ‘s’ – character variable Logic: Read the input. Call the generateIt() function. it need to two arguments. One is the input string and permutation string. ‘generateIt()’ function checks the input string is empty or not. If it is not empty, it creates a for loop. Create the permutations using recursion. Finally, print the result. Program: public class permutationString {     //User defined function to generate permutation ...

How to implement Heap Sort in java?

What is Heap sort? It is a sorting algorithm which uses a binary heap data structure.it compares the elements and organize it accordingly. It has following steps. A heap is constructed. It kept the largest element as root element. A sorting procedure is followed. The root element is exchanged with the last item. The heap is reconstructed according to heap property. This process is repeated until all elements are arranged in ascending order. Program: import java.util.Arrays; public class HeapSortEg {     public static void heapSort(int[] a) {         int n = a.length;         // let us create max heap         for (int i = n / 2 - 1; i >= 0; i--) {             heapIt(a, n, i);         }         // Extract the elem...

Create Graph using Adjacency matrix in java

       Adjacency matrix is used to represent a graph. Generally, it uses two-dimensional array for storing the value. If there is a edge between the vertex x and y, it stores the value 1. Otherwise, it stores 0 value. Java implementation: Class: GraphAdjacencyMatrixEg Member variables: adj_matrix(integer array) , g_vertices(int),src(int), dest(int), Objects: s1(Scanner object), g1(Graph object) member functions: Constructor : Initialise the values ‘addItEdge()’ : It assigns the edge value. ‘display()’ : It prints the adjacency matrix. ‘main()’ : it creates the scanner object and class object.                  It gets the edge and vertex values and connectivity between vertices.                  Call the the addItEdge and display functions to get the output. Program: import java.util...

Java Program to check the Balanced Parentheses

              This is one of the Stack Applications. To implement this concept, a stack is used to store the input. Here’s the implementation. Java implementation: Class : PaenthesisCheckerEg Variables: ‘stack1’ – new object for Stack. ‘exp’ – input expression. ‘c’ – it is a character data type. It stores a character at a time to check. ‘top’ -it stores the top element. Member functions: isitBalanced() : This function is used to check the balance. main(): it gets the input from user. Calls the isitBalanced() function and prints the result. Program: import java.util.Stack; import java.util.Scanner; public class ParenthesisCheckerEg {     public static boolean isitBalanced(String exp) {         Stack<Character> stack1 = new Stack<>();         for (char c : exp.toCharArray()) {       ...

Java implementation of Stack using Arrays

              Stack is one of the linear data structures which stores data elements. It has following operations. Push() -It is used to insert the data elements to Stack. Pop() – It performs the deletion of element. Peep() – It gives you the top element. isEmpty() -It checks for emptiness isFull() -It checks whether Stack is full or not. Program: class StackEg1 {     private int m_Size;     private int top;     private int[] sArray;     // Here comes the Constructor     public StackEg1(int size) {         this.m_Size = size;         this.sArray = new int[m_Size];         this.top = -1;     }     // insert the element onto the stack(Push)     public void push(int value) {    ...

Java Program to find the intersection of two arrays

     Intersection provides the common elements between two arrays. Let us find the intersection between two arrays in java. It has two types 1.       Using HashSet 2.       Using Sorted Arrays Both of the methods are implemented as follows. 1.Using HashSet               This method implementation uses HashSet objects. A public class is created with main() function. HashSet objects set1, is1 are created. Two arrays are created in the main() function and passed to findIt() function. ‘findIt()’ reads the arrays and store it to set1. Check the   the second array elements with set1. If both are equal, it is stored in is1. Other wise, the loop is moving to next element. Finally, the result is displayed. Program: import java.util.HashSet; import java.util.Set; public class ArrayIsEg {     public static void fin...

Count Frequency of Each Element in Array in java

               Array has similar elements. If you want to find the frequency of occurrence in each number, let us implement some java programs. There are two types to implement this concept. 1.       Using Array 2.       Using Streams 1.       Using Array: This method uses array to find the Number of occurrences. The steps are given below.. It uses a public class with two functions. ‘countit()’ It gets the array and maximum value as input. A for loop is used to find the number of occurrences. Using maximum value, each element is checked and the occurrence is printed. ‘main()’ It reads the input from the user. Call the ‘countit()’ function to get the output. Program: public class FrequencyArrayEg {     public static void countIt(int[] arr, int m_Value) {         int[] freq = new int[m_Value +...

Find Armstrong Numbers in a Given Range in java

               Armstrong Number is a number which has a unique feature in it. When you take cube of each digit and sum it, it gives the same number. Eg: 153 = 1 3 +5 3 +3 3 = 1+125+27 = 153. Java implementation of finding Armstrong Number in the given range: It starts with including the built-in header file. Create a class with two functions   itArmstrong() and findArmstrongNos(). itArmstrong() – it splits each digit separately and raise the power to 3 . ‘findArmstrongNos()’ – it finds the Armstrong number in the given range. ‘main()’ – reads the input from the user to starting and ending of the range. It calls the ‘findArmstrongNos()’ function. Program: import java.util.Scanner; public class ArmstrongNoInRangeEg {        public static boolean itArmstrong(int n) {         int originalNo = n, sum = 0, digit = 0;       ...