Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Enum.ordinal() Method in Java

Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). For example, let's have weekdays in an enum starting from Monday, Tuesday till Sunday. So the ordinal of Monday will be 0, Tuesday will be 1, etc.,

Enum.ordinal() Method in Java


Let's see simple Java for the same.


enum Days{
// 0 1  2     3         4       5  6 
 MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
}

public class EnumOrdinal {
 public static void main(String[] args) {
  Days mon = Days.MONDAY;
  Days wed = Days.WEDNESDAY;
  Days tus = Days.TUESDAY;
  Days fri = Days.FRIDAY;
  Days sun = Days.SUNDAY;
  
  System.out.println("Monday ordinal    : "+mon.ordinal());
  System.out.println("Wednesday ordinal : "+wed.ordinal());
  System.out.println("Tuesday ordinal   : "+tus.ordinal());
  System.out.println("Friday ordinal    : "+fri.ordinal());
  System.out.println("Sunday ordinal    : "+sun.ordinal());
 }
}


OUTPUT:


Monday ordinal    : 0
Wednesday ordinal : 2
Tuesday ordinal   : 1
Friday ordinal    : 4
Sunday ordinal    : 6

Find the Occurrences Of Each Character In a String

Find the Occurrences Of Each Character In a String without using collection.
Here we are going to create simple array to store the character occurrence. If we look at ASCII value of each character including space then it starts from 32 to 126. So we will create array size of 94 which can hold all the character occurrences.

Find the Occurrences Of Each Character In a String


Let's see simple example in Java how to implement in a simple way.

public class CharacterOccurrance {

 public static void main(String[] args) {
  String str = "Java Discover~";

  CharacterOccurrance obj = new CharacterOccurrance();
  int[] occurrance = obj.findCharOccurrance(str);
  obj.printOccurrance(occurrance);
 }

 public int[] findCharOccurrance(String str) {
  int[] occurrance = new int[95];
  for (int i = 0; i < str.length(); i++) {
   int index = str.charAt(i);
   occurrance[index - 32]++;
  }
  return occurrance;
 }

 public void printOccurrance(int[] occurrance) {
  System.out.println("Character : Occurrance");
  for (int i = 0; i < occurrance.length; i++) {
   if (occurrance[i] > 0) {
    char ch = (char) (i + 32);
    System.out.println(ch + " \t  : " + occurrance[i]);
   }
  }
 }
}



OUTPUT:


Character : Occurrance
     : 1          <----- Space
D    : 1
J    : 1
a    : 2
c    : 1
e    : 1
i    : 1
o    : 1
r    : 1
s    : 1
v    : 2
~    : 1

Longest palindrome Sub-sequence from the given String using Dynamic Programming

Write a program to find the longest sub-sequence palindrome from the given string by using dynamic programming. For example

Input String : ABCDQRDC

Longest sub-sequence palindrome: 5
Longest palindrome Sub-sequence from the given String using Dynamic Programming

  •  So let's see how we will solve and find the longest subsequence palindrome using dynamic programming. 

  • Construct the solution matrix of size NxN where N is the length of given string. 
  • We will calculate the size of each character sequence palindrome size and will the memorised in the solution matrix which will referred for the next incremental sequence.
  • For example in above example all strings of 1 character will be palindrome size of 1. A, B, C, D, Q, R, D, C
  • On next cycle it will add another character and makes 2 character string like 
  • AB, BC, CD, DQ, QR, RD, DC and goes on like 
  • ABC, BCD, CDQ, DQR, QRD, RDC etc.,
  • Each sequences palindrome size will be stored in the solution array and finally returns the maximum size as output.
Now lets see simple Java code 


 public class LongestPalindromeSequence {

 public static void main(String[] args) {

  String str = "ABCDQRDC";

  LongestPalindromeSequence obj = new LongestPalindromeSequence();

  System.out.println("\nLength of Longest palindrome subsequence : " + obj.lps(str));

 }

 public int lps(String seq) {
  int n = seq.length();
  int j, k, i;
  int L[][] = new int[n][n];

  // Strings of 1 character will be palindrome size of 1 
  // starting with upper matrix and all single character falls diagonally and size will be 1
  for (j = 0; j < n; j++)
   L[j][j] = 1;

  for (i = 2; i <= n; i++) {
   for (j = 0; j < n - i + 1; j++) {

    k = j + i - 1;

    if (seq.charAt(j) == seq.charAt(k)) {
     L[j][k] = L[j + 1][k - 1] + 2;

    } else {
     L[j][k] = Math.max(L[j][k - 1], L[j + 1][k]);
    }
   }
  }

  /*System.out.println("Final solution Matrix :::: ");
  for (j = 0; j < n; j++) {
   System.out.print(seq.charAt(j) +" - ");
   for (k = 0; k < n; k++) {
    System.out.print(L[j][k] + "\t");
   }
   System.out.println();
  }*/
  return L[0][n - 1];
 }
}

OUTPUT:


Length of Longest palindrome subsequence : 5

How to create a graph using Java

Let's see simple graph creation using core java and printing all the vertex along with list of edges which goes from that particular Vertex.

How to create a graph using Java




public class MyGraph {

 public static void main(String[] args) {
  
  /* Initilize graph with 5 vertex and as 
   * going to be directed graph
   */
  
  Graph myGra = new Graph(5, "directed");
  
  /*
   * Add vertex 
   */
  myGra.addVertex("A");
  myGra.addVertex("B");
  myGra.addVertex("C");
  myGra.addVertex("D");
  myGra.addVertex("E");
  
  /*
   * Add edges between each vertex and their distance 
   */
  myGra.addEdge("A", "B",5);
  myGra.addEdge("A", "E",1);
  myGra.addEdge("B", "C",2);
  myGra.addEdge("C", "D",2);
  myGra.addEdge("E", "D",2);
  myGra.addEdge("E", "A",2);
  
  // Print the created graph
  myGra.printMyGraph();
  
 }
}




public class Graph {

 // Graph direction (directed / undirected graph)
 private boolean undirected = true;
 
 // No. of vertex in the graph
 private Vertex[] arrayOfVertex;
 
 private int indexCounter = 0;
 
 // Constructor to create graph vertex 
 public Graph(int noOfVertex, String graphType) {
  if (graphType.equalsIgnoreCase("directed")) {
   this.undirected = false;
  }
  arrayOfVertex = new Vertex[noOfVertex];
 }
 
 // Vertex class
 class Vertex {
  // Name of the Vertex
  private String name;
  
  // Holds the list of all edges from current vertex 
  private Edge edge;

  // Create vertex 
  public Vertex(String name, Edge aNode) {
   this.name = name;
   this.edge = aNode;
  }
 }
 
 // Edge between 2 Vertex
 class Edge {
  // Destination vertex Id
  private int vertexId;
  
  // In list point to next edge if its else null 
  private Edge next;
  
  // Weight of current edge
  private int weight;

  // Create edge
  public Edge(int vertexId, Edge next, int weight) {
   this.vertexId = vertexId;
   this.next = next;
   this.weight = weight;
  }
 }

 // Adding Vertex 
 public void addVertex(String vertexName) {
  arrayOfVertex[indexCounter] = new Vertex(vertexName, null);
  indexCounter++;
 }

 // Adding Edge
 public void addEdge(String sVertex, String dVertex, int weight) {
  int sId = indexOfName(sVertex);
  int dId = indexOfName(dVertex);

  /*
   * Find source and destination vertexId and create new Edge and 
   * point it to source edge link
   */
  arrayOfVertex[sId].edge = new Edge(dId, arrayOfVertex[sId].edge, weight);
  
  /*
   * If undirected then create 2 edge's between source and destination and 
   * destination to source 
   */
  if (undirected) {
   arrayOfVertex[dId].edge = new Edge(sId, arrayOfVertex[dId].edge, weight);
  }
 }

 /*
  * Getting indexId of given vertex name
  */
 private int indexOfName(String name) {
  for (int v = 0; v < arrayOfVertex.length; v++) {
   if (arrayOfVertex[v].name.equals(name)) {
    return v;
   }
  }
  return -1;
 }

 /*
  * Print the graph in vertex order and listing all outgoing edges from that vertex
  */
 public void printMyGraph() {
  System.out.println("VERTEX\t----> EDGES WITH WEIGHT");
  for (int v = 0; v < arrayOfVertex.length; v++) {
   System.out.print(arrayOfVertex[v].name +" \t ----> ");
   for (Edge aNode = arrayOfVertex[v].edge; aNode != null; aNode = aNode.next) {
    System.out.print( "<==>"+ arrayOfVertex[aNode.vertexId].name + ":" + aNode.weight);
   }
   System.out.println();
  }

 }
}



OUTPUT:


VERTEX         ----> EDGES WITH WEIGHT
A          ----> <==>E:1<==>B:5
B          ----> <==>C:2
C          ----> <==>D:2
D          ----> 
E          ----> <==>A:2<==>D:2

Reverse words in a given String using recursion

Reverse words in a given String using recursion. We need to reverse words by words in a given line and not the character in a given string. We need to solve this by using backtracking and recursion logic.
Reverse words in a given String using recursion

Let's see simple Java code for getting the given of words in a reverse order by using recursion.


public class ReverseLineByWords {

 public static void main(String[] args) {
  
  String str = "Hello Java Discover";
  
  String finalStr = new ReverseLineByWords().reverseLine(str);
  
  System.out.println(finalStr);
  
 }
 
 public String reverseLine(String str){
  String word = "";
  int i = 0;
  for(;i<str.length();i++){
   if(str.charAt(i) == ' ') {
    word = word + " ";
    break;
   }else{
    word = word + str.charAt(i);
   }
  }

  if(i < str.length()) 
   return reverseLine(str.substring(i+1)) + word;
  
  return (word + " ");
 }
}


OUTPUT:


Discover Java Hello 


Rotate matrix by clockwise

Given a NxN matrix and need to rotate by clockwise as given below

Examples:
Rotate matrix by clockwise


Let's see simple java code to rotate given NxN matrix.


public class MatrixRotate {

 private int prev, curr;

 public static void main(String[] args) {

  int[][] matrix = new int[][] { { 1, 2, 3, 4 }, 
                   { 5, 6, 7, 8 }, 
            { 9, 10, 11, 12 }, 
            { 13, 14, 15, 16 } };
  

  MatrixRotate obj = new MatrixRotate();
  obj.rotateMatrix(matrix);

  for (int i = 0; i < matrix.length; i++) {
   System.out.println();
   for (int j = 0; j < matrix[0].length; j++) {
    System.out.print(matrix[i][j] + ", ");
   }
  }
 }

 public void rotateMatrix(int[][] matrix) {

  int r = matrix.length;
  int c = matrix[0].length;
  int row = 0, col = 0;

  for (int cnt = 0;cnt<(r*c);cnt++) {
   
   prev = matrix[row + 1][col];

   for (int i = col; i < c; i++) {
    swap(row, i, matrix); cnt++;   }
   row++;

   for (int i = row; i < r; i++) {
    swap(i, c - 1, matrix); cnt++;   }
   c--;

   if (row < r) {
    for (int i = c - 1; i >= col; i--) {
     swap(r - 1, i, matrix); cnt++;
    }
   }
   r--;

   if (col < c) {
    for (int i = r - 1; i >= row; i--) {
     swap(i, col, matrix); cnt++;
    }
   }
   col++;
  }
 }

 public void swap(int i, int j, int matrix[][]) {
  curr = matrix[i][j];
  matrix[i][j] = prev;
  prev = curr;
 }
}


OUTPUT:


 5,  1,  2,  3, 
 9, 10,  6,  4, 
13, 11,  7,  8, 
14, 15, 16, 12, 



Find the smallest window in a string containing all characters of another string (With smallest window)

Given two strings string1 and string2, find the smallest substring in string1 containing all characters of string2 efficiently.
For Example:
Find the smallest window in a string containing all characters of another string (With smallest window)
Steps:
  • Generate all substrings which starts with any one character from the pattern string
  • Iterate all substrings which we generated and compare each character from the pattern string with the substring and check for all characters present or not
  • If all characters present in substring then trim extra characters and choose the smallest window string

Java code:


public class StringInSmallestWindow {

 public static void main(String[] args) {

  String str = "niharika";
  String findStr = "ir";
  String result = null;

  if (str.length() < findStr.length()) {
   System.out.println("Pattern string is greater than source string");
   return;
  }

  int j = 0;
  String[] arr = new String[str.length()];
  // Get all substring which starts with any one character from the
  // pattern string
  for (int i = 0; i < str.length(); i++) {
   if (findStr.contains(str.charAt(i) + "") && str.substring(i).length() >= findStr.length()) {
    arr[j++] = str.substring(i);
   }
  }

  // Iterate all substrings which we generated
  for (int pnt = 0; pnt < j; pnt++) {

   String string = arr[pnt];
   char[] tmp = findStr.toCharArray();

   int cnt = tmp.length;
   int lastIndex = 0;

   // Compare each character from the pattern string with the substring
   // and check for all characters present or not
   for (int i = 0; i < tmp.length; i++) {

    if (string.contains(tmp[i] + "")) {
     if (lastIndex < string.indexOf(tmp[i])) {
      lastIndex = string.indexOf(tmp[i]);
     }
     string = string.substring(0, string.indexOf(tmp[i])) + '\0'
       + string.substring(string.indexOf(tmp[i]) + 1);
     tmp[i] = '\0';
     cnt--;
    }
   }

   // If all characters present in substring then trim extra characters
   // and choose the smallest window string
   if (cnt <= 0) {
    arr[pnt] = arr[pnt].substring(0, lastIndex + 1);
    result = arr[pnt].length() < result.length() ? arr[pnt] : result;
   }

  }
  System.out.println("\nInput String           : " + str);
  System.out.println("\n2nd String to find     : " + findStr);
  System.out.println("\nSmallest window string : " + result);
 }
}


OUTPUT:


Input String           : niharika

2nd String to find     : ir

Smallest window string : ri

How to find missing number in a sequential array ?

 
Given a list of sequential integers and need to finding a missing number from the list of numbers. For example if we have an array like

Finding missing number


Example:1
array = {1,2,3,5,6}
Finding missing number 4

Example:2
array = {14,15,16,18,19,20}
then the missing number is 17

Using XOR operation and finding the missing number.

  • Iterate all the elements and do XOR with each other. 
  • Iterate all the numbers between given smallest and greatest number. In our above example between 1 to 6 and 14 to 20.
  • Next do XOR with both results which gives the missing number

Lets see simple Java code implementation



public class FindingMissingNumber {

 public static void main(String[] args) {
  
  int[] arr = new int[]{11,12,13,15,16,17,18,19};
  int sr = 11;
  int er = 19;
  
  FindingMissingNumber obj = new FindingMissingNumber();
  
  System.out.println("Missing number using XOR : "+obj.findMissingNumberUsingXOR(arr, sr, er));
 }
 
 public int findMissingNumberUsingXOR(int[] arr, int sr, int er){
  
  int xor = 0;
  int actualXor = 0;
  
  for(int i=0;i<arr.length;i++){
   xor = xor ^ arr[i];;
  }
  
  for(int i=sr;i<=er;i++){
   actualXor = actualXor ^ i;
  }
  
  return (xor ^ actualXor);
 }
}



OUTPUT:



Missing number using XOR : 14




Split the array into two equal Sum subarrays

Given an array of integers greater than zero, find it possible to split it in two subarrays such that the sum of the two subarrays is the same or with minimal difference. Print the two subarrays.
Split the array into two equal Sum subarrays


Examples:

Input: {5,7,9,2,69,23,9,1,8,5,7,3,6,16}

Output
1st Array sum  : 85
2nd Array sum : 85

ARRAY-1 : 69, 8, 7, 1, 
ARRAY-2 : 23, 2, 16, 3, 9, 5, 9, 5, 6, 7, 


Input: {1,2,3,4,5,6,7,8,9,10}

Output:
1st Array sum  : 27
2nd Array sum : 28

ARRAY-1 : 10, 8, 2, 6, 1, 
ARRAY-2 : 9, 3, 7, 4, 5, 


Lets see simple solution how to split the given array with equal sum or minimal difference.

Steps:
1. Sort the given array.
2. Iterate the array from both end and place the values in 2 different arraylist and also maintain the sum of both list.
3. On each iteration check for both sum difference and if they are not equal then swap difference value from 1st array to 2nd array or wise-verse to make it equal or minimal difference between both the array. 
4. Finally print both the array sum and list of elements in both array.

Simple java code for the above solution:


import java.util.ArrayList;
import java.util.List;

public class ArrayPartition {

 public static void main(String[] args) {
  
  int[] array = new int[] {5,7,9,2,69,23,9,1,8,5,7,3,6,16};
  //int[] array = new int[] {1,2,3,4,5,6,7,8,9,10,1,3,3,6};
  //int[] array = new int[] {5,5,2,2,1,1,2};
  //int[] array = new int[] {1,2,3,4,5,6,7,8,9,10};
  //int[] array = new int[] {100,50,55,2,2,1};
  //int[] array = new int[] {1 , 2 , 3 , 6, 12};
  //int[] array = new int[] {1,2,3,4};
  //int[] array = new int[] {1000, 5000, 3000, 1000};
  //int[] array = new int[] {1,2,3,4,5,6,7};
  //int[] array = new int[] {1,1,1,1,1,1,2,4,2,2,1,3};
  //int[] array = new int[] {10,100,50,110};
  //int[] array = new int[] {4, 1, 2, 3};
  //int[] array = new int[] {500000, 1,332234,3565, 332234};
  
  // Sort the given array
  sortArray(array);
  
  // Call partition method to split the array
  partition(array);
  
 }

 public static void partition(int[] array) {

  List<Integer> arr1 = new ArrayList<Integer>();  
  List<Integer> arr2 = new ArrayList<Integer>();  
  
  int sum1 = 0, sum2 = 0;
  
  // Place last value (largest) value in array1
  arr1.add(array[array.length-1]);
  sum1 = array[array.length-1];


  // Iterate remaining values in array
  for (int i=0,j=array.length-2;i<=j;) {
   
   if(sum2 <= sum1) {
    arr2.add(array[i]); 
    sum2 += array[i]; 
    i++;
   }else {
    arr1.add(array[i]); 
    sum1 += array[i]; 
    i++;
   }
 
   if(i <= j) {
    if(sum2 <= sum1) {
     arr2.add(array[j]); 
     sum2 += array[j]; 
     j--;
    }else {
     arr1.add(array[j]); 
     sum1 += array[j]; 
     j--;
    }
   }
   }
   // Reorder array1 and array2 with equal sum or minimal sum
   if(sum1 > sum2) {
    int diff = (sum1 - sum2)/2;
    if(arr1.contains(diff) && diff > 0) {
     int sum[] = replaceArrayElement(arr1, diff, arr2, sum1, sum2);
     sum1 = sum[0];
     sum2 = sum[1];
     
    }
    
    while(sum1 > sum2 && diff > 0) {
     diff--;
     if(arr1.contains(diff) && diff > 0) {
      int sum[] = replaceArrayElement(arr1, diff, arr2, sum1, sum2);
      sum1 = sum[0];
      sum2 = sum[1];
      diff++;
     }
    }
   }
   
   // Reorder array1 and array2 with equal sum or minimal sum
   if(sum2 > sum1) {
    int diff = (sum2 - sum1)/2;
    if(arr2.contains(diff) && diff > 0) {
     int sum[] = replaceArrayElement(arr2, diff, arr1, sum2, sum1);
     sum2 = sum[0];
     sum1 = sum[1];
    }
    
    while(sum2 > sum1 && diff > 0) {
     diff--;
     if(arr2.contains(diff) && diff > 0) {
      int sum[] = replaceArrayElement(arr2, diff, arr1, sum2, sum1);
      sum2 = sum[0];
      sum1 = sum[1];
      diff++;
     }
    }
   }
  
  System.out.println("1st Array sum  : "+sum1);
  System.out.println("2nd Array sum : "+sum2);
  
  System.out.print("\nARRAY-1 : ");
  for (Integer integer : arr1) {
   System.out.print(integer +", ");
  }
  
  
  System.out.print("\nARRAY-2 : ");

  for (Integer integer : arr2) {
   System.out.print(integer +", ");
  }
 }
 
 private static int[] replaceArrayElement(List<Integer> arr1, int diff, List<Integer> arr2, int sum1, int sum2) {
  
  int in = arr1.indexOf(diff);
  arr1.remove(in);
  sum1 = sum1 - diff;
  arr2.add(diff);
  sum2 = sum2 + diff;
  
  return new int[] {sum1, sum2};
 }

 private static void sortArray(int[] array) {

  for(int i=0;i<=array.length-1;i++) {
   for(int j=i+1;j<=array.length-1;j++) {
    if(array[i] > array[j]) {
     int tmp = array[i];
     array[i] = array[j];
     array[j] = tmp;
    }
   }
  }
 }
}

OUTPUT:


1st Array sum  : 85
2nd Array sum : 85

ARRAY-1 : 69, 8, 7, 1, 
ARRAY-2 : 23, 2, 16, 3, 9, 5, 9, 5, 6, 7,