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 countIt() function to get the counting value.  

Program:

import java.util.*;

public class CCCGEg {

    private static void g_dfs(int g_node, List<List<Integer>> g_adjList, boolean[] g_visited) {

        g_visited[g_node] = true;

        for (int neighbor : g_adjList.get(g_node)) {

            if (!g_visited[neighbor]) {

                g_dfs(neighbor, g_adjList, g_visited);

            }

        }

    }

    public static int countIt(int n, int[][] edges) {

        List<List<Integer>> g_adjList = new ArrayList<>();

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

            g_adjList.add(new ArrayList<>());

        }

        for (int[] edge : edges) {

            g_adjList.get(edge[0]).add(edge[1]);

            g_adjList.get(edge[1]).add(edge[0]);

        }

        boolean[] g_visited = new boolean[n];

        int count = 0;

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

            if (!g_visited[i]) {

                g_dfs(i, g_adjList, g_visited);

                count++;

            }

        }

        return count;

    }

    public static void main(String[] args) {

        int n = 4;

        int[][] edges = {{0, 2},{2, 3}, {3,1}};

        System.out.println("The Count of connected components are: " + countIt(n, edges));

    }

}

Output:

C:\raji\blog>javac CCCGEg.java

C:\raji\blog>java CCCGEg

The Count of connected components are: 1

This is the way of creating the java program to count the connected components in a graph was done. Hope, this code gives you clear understanding to you. Keep coding!!!  

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 {

    public static void main(String[] args) {

        int[] set1 = {4, 2, 5}; //elements assignement

        List<List<Integer>> subset1 = findSubset(set1, 0);

        System.out.println(subset1);

    }

    public static List<List<Integer>> findSubset(int[] set1, int index) {

        List<List<Integer>> all_Subsets;

        if (index == set1.length) {

            all_Subsets = new ArrayList<>();

            all_Subsets.add(new ArrayList<>()); // insert empty set

        } else {

            all_Subsets = findSubset(set1, index + 1);

            int s_item = set1[index];

            List<List<Integer>> moreSubsets = new ArrayList<>();

            for (List<Integer> subset : all_Subsets) {

                List<Integer> new_Subset = new ArrayList<>(subset);

                new_Subset.add(s_item);

                moreSubsets.add(new_Subset);

            }

            all_Subsets.addAll(moreSubsets);

        }

        return all_Subsets;

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac SubsetFinderEg.java

C:\raji\blog>java SubsetFinderEg

[[], [5], [2], [5, 2], [4], [5, 4], [2, 4], [5, 2, 4]]

Yes. That’s the output.

Here the set has 3 elements [4,2,5]

The sub sets are [], each element separately [2],[4],[5], combination of two elements [5,2],[5,4],[2,4] and finally all number combinations [5,2,4].

This is the way of creating subsets from a set using java. Hope,this code will useful to you. Keep Coding!!!!

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;

    }

 

    @Override

    public int compareTo(HuffmanNode other) {

        return this.h_freq - other.h_freq;

    }

}

 

// class for Huffman Encoding technique

public class HuffmanEncodingEg {

    public static Map<Character, String> huffmanCodes = new HashMap<>();

    // recursive method to generate Huffman code

    public static void generateIt(HuffmanNode root, String code) {

        if (root == null) return;

        if (root.h_left == null && root.h_right == null) {

            huffmanCodes.put(root.h_char, code);

        }

        generateIt(root.h_left, code + "0");

        generateIt(root.h_right, code + "1");

    }

    // Develop the Huffman Tree and code

    public static Map<Character, String> buildHuffmanTree(Map<Character, Integer> freqMap) {

        PriorityQueue<HuffmanNode> pq1 = new PriorityQueue<>();

        for (Map.Entry<Character, Integer> entry : freqMap.entrySet()) {

            pq1.add(new HuffmanNode(entry.getKey(), entry.getValue()));

        }

        while (pq1.size() > 1) {

            HuffmanNode h_left = pq1.poll();

            HuffmanNode h_right = pq1.poll();

            HuffmanNode newNode = new HuffmanNode('-', h_left.h_freq + h_right.h_freq);

            newNode.h_left = h_left;

            newNode.h_right = h_right;

            pq1.add(newNode);

        }

        HuffmanNode root = pq1.poll();

        generateIt(root, "");

        return huffmanCodes;

    }

    public static void main(String[] args) {

        String txt = "It is huffman coding Sample";

        Map<Character, Integer> freqMap1 = new HashMap<>();

        for (char c : txt.toCharArray()) {

            freqMap1.put(c, freqMap1.getOrDefault(c, 0) + 1);

        }

        Map<Character, String> huffmanCodes = buildHuffmanTree(freqMap1);

        System.out.println("The Huffman Codes are:");

        for (Map.Entry<Character, String> entry : huffmanCodes.entrySet()) {

            System.out.println(entry.getKey() + ": " + entry.getValue());

        }

    }

}

Output:

C:\raji\blog>javac HuffmanEncodingEg.java

C:\raji\blog>java HuffmanEncodingEg

The Huffman Codes are:

p: 00

a: 101

S: 111

e: 110

l: 100

m: 01

Hope this code will help you! Keep coding!!!!

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 the member functions.

ch -character element.

‘insert()’ – add the elements to the structure.

‘search()’ -it finds an elements.

‘startWith()’ – it checks the data starts with a particular data or not.

Program:

import java.util.*;

class TrieNodeEg {

    Map<Character, TrieNodeEg> children;

    boolean isEOF;

    public TrieNodeEg() {

        children = new HashMap<>();

        isEOF = false;

    }

}

class TrieEg {

    private TrieNodeEg t_root;

    public TrieEg() {

        t_root = new TrieNodeEg();

    }

    public void insert(String wrd) {

        TrieNodeEg t_node = t_root;

        for (char ch : wrd.toCharArray()) {

            t_node.children.putIfAbsent(ch, new TrieNodeEg());

            t_node = t_node.children.get(ch);

        }

        t_node.isEOF = true;

    }

    public boolean search(String wrd) {

        TrieNodeEg t_node = t_root;

        for (char ch : wrd.toCharArray()) {

            if (!t_node.children.containsKey(ch)) {

                return false;

            }

            t_node = t_node.children.get(ch);

        }

        return t_node.isEOF;

    }

    public boolean startsWith(String prefix) {

        TrieNodeEg t_node = t_root;

        for (char ch : prefix.toCharArray()) {

            if (!t_node.children.containsKey(ch)) {

                return false;

            }

            t_node = t_node.children.get(ch);

        }

        return true;

    }

}

public class TrieSample {

    public static void main(String[] args) {

        TrieEg trie1 = new TrieEg();

        trie1.insert("Car");

        trie1.insert("Vehicle");

        trie1.insert("Bus");

        System.out.println(trie1.search("Car"));

        System.out.println(trie1.search("Vehicle"));  

        System.out.println(trie1.search("Van")); 

        System.out.println(trie1.startsWith("Bus"));

    }

}

Output:

C:\raji\blog>javac TrieSample.java

C:\raji\blog>java TrieSample

true

true

false

true

This is the way of creating Word search application using Trie Structure in java. Hope, this code is beneficial to you. Keep coding!!!!

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_row, '.');

        backtracking(board1, 0, n);

    }

    private static void backtracking(char[][] board1, int q_row, int n) {

        if (q_row == n) {

            printItBoard(board1);

            return;

        }

        for (int q_col = 0; q_col < n; q_col++) {

            if (isItSafe(board1, q_row, q_col, n)) {

                board1[q_row][q_col] = 'Q';

                backtracking(board1, q_row + 1, n);

                board1[q_row][q_col] = '.';

            }

        }

    }

    private static boolean isItSafe(char[][] board1, int q_row, int q_col, int n) {

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

            if (board1[i][q_col] == 'Q') return false;

        }

        for (int i = q_row, j = q_col; i >= 0 && j >= 0; i--, j--) {

            if (board1[i][j] == 'Q') return false;

        }

        for (int i = q_row, j = q_col; i >= 0 && j < n; i--, j++) {

            if (board1[i][j] == 'Q') return false;

        }

        return true;

    }

    private static void printItBoard(char[][] board1) {

        for (char[] q_row : board1) {

            System.out.println(new String(q_row));

        }

        System.out.println();

    }

    public static void main(String[] args) {

        int n = 4;

        solveNQueensPbm(n);

    }

}

Output:

C:\raji\blog>javac NQueensEg.java

C:\raji\blog>java NQueensEg

.Q..

...Q

Q...

..Q.

 

..Q.

Q...

...Q

.Q..

This output has 4 columns in each row. Q refers ‘queens’. It does not cross each other.

That’s the way, the Java Program to implement N queens Problem was done successfully. Keep coding!!!

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

    public static void generateIt(String str1, String perm1) {

        if (str1.isEmpty()) {

            System.out.println(perm1);

            return;

        }

       //for loop to create permutaions

        for (int i = 0; i < str1.length(); i++) {

            char s = str1.charAt(i);

            String s_remaining = str1.substring(0, i) + str1.substring(i + 1);

            generateIt(s_remaining, perm1 + s);

        }

    }

    //main() function

    public static void main(String[] args) {

        String sample = "XYZ";

        System.out.println("Permutations of " + sample + ":");

        generateIt(sample, "");

    }

}

Output:

Compile and execute the program to get the output.

C:\raji\blog>javac permutationString.java

C:\raji\blog>java permutationString

Permutations of XYZ:

XYZ

XZY

YXZ

YZX

ZXY

ZYX

That’s all. The Java Program to generate the permutations using String is done. Keep Coding!!!

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 elements one by one

        for (int i = n - 1; i > 0; i--) {

            // Exchange the root element with the last element

            int temp = a[0];

            a[0] = a[i];

            a[i] = temp;

            // check for Heap if it is reduced

            heapIt(a, i, 0);

        }

    }

    private static void heapIt(int[] a, int n, int i) {

        int large = i;

        int a_left = 2 * i + 1;

        int a_right = 2 * i + 2;

        // If the left child is greater than root

        if (a_left < n && a[a_left] > a[large]) {

            large = a_left;

        }

        // If the right child is greater than largest so far

        if (a_right < n && a[a_right] > a[large]) {

            large = a_right;

        }

        // Check the largest number is not root

        if (large != i) {

            int swap = a[i];

            a[i] = a[large];

            a[large] = swap;

            // Recursively heapIt the affected sub-tree

            heapIt(a, n, large);

        }

    }

    public static void main(String[] args) {

        int[] a = {22, 10, 31, 15, 61, 87, 3, 16};

        System.out.println("Original array is: " + Arrays.toString(a));

        heapSort(a);

        System.out.println("The Sorted array: " + Arrays.toString(a));

    }

}

Output:

C:\raji\blog>javac HeapSortEg.java

C:\raji\blog>java HeapSortEg

Original array is: [22, 10, 31, 15, 61, 87, 3, 16]

The Sorted array: [3, 10, 15, 16, 22, 31, 61, 87]

This is the simple way to create the Heap sort in java. Hope, this code is useful to you. Keep Coding!!!

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.Scanner;

public class GraphAdjacencyMatrixEg {

    private int[][] adj_Matrix;

    private int g_vertices;

    public GraphAdjacencyMatrixEg(int g_vertices) {

        this.g_vertices = g_vertices;

        adj_Matrix = new int[g_vertices][g_vertices];

    }

    public void addItEdge(int src, int dest) {

        adj_Matrix[src][dest] = 1;

        adj_Matrix[dest][src] = 1; // it is an undirected graph

    }

    public void display() {

        System.out.println("The Adjacency Matrix:");

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

            for (int j = 0; j < g_vertices; j++) {

                System.out.print(adj_Matrix[i][j] + " ");

            }

            System.out.println();

        }

    }

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        System.out.print("Enter the number of vertices: ");

        int g_vertices = s1.nextInt();

        GraphAdjacencyMatrixEg g1 = new GraphAdjacencyMatrixEg(g_vertices);

        System.out.print("Enter the number of edges: ");

        int edges = s1.nextInt();

        System.out.println("Enter the edges in this order like (source destination):");

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

            int src = s1.nextInt();

            int dest = s1.nextInt();

            g1.addItEdge(src, dest);

        }

        g1.display();

        s1.close();

    }

}

Output:

C:\raji\blog>javac GraphAdjacencyMatrixEg.java

C:\raji\blog>java GraphAdjacencyMatrixEg

Enter the number of vertices: 4

Enter the number of edges: 4

Enter the edges in this order like (source destination):

0 1

1 2

2 3

3 2

The Adjacency Matrix:

0 1 0 0

1 0 1 0

0 1 0 1

0 0 1 0

That’s all . The java implementation of Graph using adjacency matrix is done. Keep coding!!!

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()) {

            // check if it is an opening bracket, push it onto the stack

            if (c == '(' || c == '{' || c == '[') {

                stack1.push(c);

            }

            // check if it's a closing bracket, check if it matches the top of the stack

            else if (c == ')' || c == '}' || c == ']') {

                if (stack1.isEmpty()) return false;

                char top = stack1.pop();

                if ((c == ')' && top != '(') ||

                    (c == '}' && top != '{') ||

                    (c == ']' && top != '[')) {

                    return false;

                }

            }

        }

        // check for stack is empty at the end, parentheses are balanced

        return stack1.isEmpty();

    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a input with parenthesis ( [ {: ");

        String exp = scanner.nextLine();

        if (isitBalanced(exp)) {

            System.out.println("The expression with parentheses is balanced.");

        } else {

            System.out.println("The expression is not balanced.");

        }

    }

}

Output:

C:\raji\blog>javac ParenthesisCheckerEg.java

C:\raji\blog>java ParenthesisCheckerEg

Enter a input with parenthesis ( [ {: {[()]}

The expression with parentheses is balanced.

C:\raji\blog>java ParenthesisCheckerEg

Enter a input with parenthesis ( [ {: ({}]

The expression is not balanced.

This is the simple java implementation of  Balanced ParenthesisChecker. Hope this code is useful to you. Keep Coding!!!

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) {

        if (isFull()) {

            System.out.println("The Stack is full with elements.Cannot push any element " + value);

            return;

        }

        sArray[++top] = value;

    }

 

    // Delete the element from the stack(pop)

    public int pop() {

        if (isEmpty()) {

            System.out.println("The Stack has no elements. Cannot pop the elements.");

            return -1;

        }

        return sArray[top--];

    }

    // Peek the top element

    public int peek() {

        if (isEmpty()) {

            System.out.println("The Stack is empty. It Cannot peek.");

            return -1;

        }

        return sArray[top];

    }

    // Check for the stack emptiness

    public boolean isEmpty() {

        return (top == -1);

    }

    // Check if the stack is full or not

    public boolean isFull() {

        return (top == m_Size - 1);

    }

    public static void main(String[] args) {

        StackEg1 stack1 = new StackEg1(10);

        stack1.push(11);

        stack1.push(22);

        stack1.push(33);

        stack1.push(44);

        stack1.push(55);

        System.out.println("The top element is: " + stack1.peek());

        System.out.println("The Popped element is: " + stack1.pop());

        System.out.println("The Popped element is: " + stack1.pop());

        System.out.println("The top element is:" + stack1.peek());

        stack1.push(66);

        System.out.println("The top element is after pushing an element:" + stack1.peek());

        if( stack1.isEmpty())

        {

        System.out.println("The stack is empty ");

        }

        else

        {

        System.out.println("The stack is not empty");

        }

    }

}

Output:

C:\raji\blog>javac StackEg1.java

C:\raji\blog>java StackEg1

The top element is: 55

The Popped element is: 55

The Popped element is: 44

The top element is:33

The top element is after pushing an element:66

Thus, the Java Program to implement the Stack using Arrays was done. Keep coding!!!

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. 1.      Using HashSet
  2. 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 findIt(int[] a1, int[] a2) {

        Set<Integer> set1 = new HashSet<>();

        Set<Integer> is1 = new HashSet<>();

        // Let us insert elements of first array to the set

        for (int no : a1) {

            set1.add(no);

        }

        // let us find if there is any common elements

        for (int no : a2) {

            if (set1.contains(no)) {

                is1.add(no);

            }

        }

        // The common elements are displayed here

        System.out.println("Intersection of Arrays: " + is1);

    }

    public static void main(String[] args) {

        int[] a1 = {11, 22, 33, 44, 55};

        int[] a2 = {44, 55, 16, 77};

        findIt(a1, a2);

    }

}

Output:

C:\raji\blog>javac ArrayIsEg.java

C:\raji\blog>java ArrayIsEg

Intersection of Arrays: [55, 44]

2.Using Sorted Arrays

              This method reads two arrays as input and pass it to ‘findIt()’ method.

  • ‘findIt()’ method sorts both of array.
  • Both of the arrays are compared, if any common elements are there, it prints the element.
  • Otherwise, it moves to next element.

Program:

import java.util.Arrays;

public class SortedArrayIs {

    public static void findIt(int[] a1, int[] a2) {

        Arrays.sort(a1);

        Arrays.sort(a2);

        int i = 0, j = 0;

        System.out.print("Intersection of Arrays: ");

        while (i < a1.length && j < a2.length) {

            if (a1[i] == a2[j]) {

                System.out.print(a1[i] + " ");

                i++;

                j++;

            } else if (a1[i] < a2[j]) {

                i++;

            } else {

                j++;

            }

        }

    }

    public static void main(String[] args) {

        int[] a1 = {11, 21, 31, 41, 51};

        int[] a2 = {31, 41, 51, 61, 71};

        findIt(a1, a2);

    }

}

Output:

C:\raji\blog>javac SortedArrayIs.java

C:\raji\blog>java SortedArrayIs

Intersection of Arrays: 31 41 51

This is the way of implementing the intersection of two arrays in java. Hope, this code is useful to you.  Keep Coding!!!

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. 1.      Using Array
  2. 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 + 1];

        // Count the number of occurrences

        for (int no : arr) {

            freq[no]++;

        }

        // Print frequencies of the occurrences

        System.out.println("The Element Frequencies:");

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

            if (freq[i] > 0) {

                System.out.println(i + " -> " + freq[i]);

            }

        }

    }

    public static void main(String[] args) {

        int[] a = {31, 11, 22, 31, 4,11, 32,45};

        countIt(a, 45);

    }

}

Output:

C:\raji\blog>javac FrequencyArrayEg.java

C:\raji\blog>java FrequencyArrayEg

The Element Frequencies:

4 -> 1

11 -> 2

22 -> 1

31 -> 2

32 -> 1

45 -> 1

2.Using Streams:

              This program uses streams to find the frequency of occurences.

  • It includes the built in packages.
  • A public class with main() is developed.
  • An integer array is created with values.
  • A long int variable is declared from Map. using built in functions, the frequency of occurrences is found and printed.

Program:

import java.util.Arrays;

import java.util.Map;

import java.util.stream.Collectors;

public class FrequencyStreamsEg {

    public static void main(String[] args) {

        int[] a = {41, 22, 13, 41, 22, 2, 13, 53, 16, 41};

        Map<Integer, Long> fMap = Arrays.stream(a)

            .boxed()

            .collect(Collectors.groupingBy(num -> num, Collectors.counting()));

        System.out.println("The Element Frequencies: " + fMap);

    }

}

Output:

C:\raji\blog>javac FrequencyStreamsEg.java

C:\raji\blog>java FrequencyStreamsEg

The Element Frequencies: {16=1, 2=1, 53=1, 22=2, 41=3, 13=2}

Yes. That’s the way to count the frequency of each element in array was developed in java. Keep Coding!!!

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 = 13 +53 +33 = 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;

        // Code to count the number of digits

        int temp = n;

        while (temp > 0) {

            digit++;

            temp /= 10;

        }

        // To find the sum of digits raised to the power of digits

        temp = originalNo;

        while (temp > 0) {

            int digi = temp % 10;

            sum += Math.pow(digi, digit);

            temp /= 10;

        }

        return sum == originalNo;

    }

     // Let us find Armstrong numbers in a given range

    public static void findArmstrongNos(int s, int e) {

        System.out.println("Armstrong Numbers between " + s + " and " + e + ":");

        for (int no = s; no <= e; no++) {

            if (itArmstrong(no)) {

                System.out.print(no + " ");

            }

        }

        System.out.println();

    }

    public static void main(String[] args) {

        Scanner s1 = new Scanner(System.in);

        // Input statements

        System.out.print("Enter the start of range: ");

        int st = s1.nextInt();

        System.out.print("Enter the end of range: ");

        int en = s1.nextInt();

        findArmstrongNos(st, en);

        s1.close();

    }

}

Output:

C:\raji\blog>javac ArmstrongNoInRangeEg.java

C:\raji\blog>java ArmstrongNoInRangeEg

Enter the start of range: 123

Enter the end of range: 1045

Armstrong Numbers between 123 and 1045:

153 370 371 407

That’s it. The java program to find Armstrong number in the given range is done. Hope, this code is easily understandable to you. Keep Coding!!!