Saturday, 23 July 2016

Check whether a string is a rotation of another string using Java .....

here is the code....

Problem - "ravgau" is a rotation of "gaurav".



       

public class Demo {

 public static void main(String[] args) {

  String s1 = "gaurav";
  String s2 = "avgaur";

  if (isSubString(s1 + s1, s2))
   System.out.print("String :" + s2 + " is a rotation of string :" + s1);
  else
   System.out.print("String :" + s2 + " is not a rotation of string :" + s1);

 }

 public static boolean isSubString(String s1, String s2) {
  int k = 0;
  int i = 0;
  int t;
  if (s1.length() < s2.length()) {
   return false;
  } else {
   while (i < (s1.length() - s2.length() + 1)) {
    if (s1.charAt(i) == s2.charAt(k)) {
     t = i;
     t++;
     k++;
     // Always make sure that conditions in loop should appear in
     // correct order otherwise it could give an exception
     while ((k < s2.length()) && (s1.charAt(t) == s2.charAt(k))) {
      t++;
      k++;
     }
     if (k == s2.length())
      return true;
     else
      k = 0;
    }
    i++;
   }
  }
  return false;
 }
}

       
 

Remove duplicates from a string without using any additional data structure using Java....

here is the code .....


       

public class Demo {

 public static void main(String[] args) {
  String name = "GAURAV KUMAR YADAV1111";
  dupliactesRemoved(name);
 }

 //This method assumes that string is made up of only small letter characters i. "a....z"
 public static void dupliactesRemoved(String temp) {

  int vector = 0;
  int val;
  System.out.println("Given string after removing duplicates characters is below :");
  for (int i = 0; i < temp.length(); i++) {
   val = temp.charAt(i) - 'a';
   if ((vector & (1 << val)) == 0) {
    System.out.print(temp.charAt(i));
    vector = vector | (1 << val);
   }
  }
 }
}

       
 

Determine if a string has all unique characters without using any additional data structure using Java....

Here is the the code ....



       
public class Demo {

 public static void main(String[] args) {

  String name = "gaurv1";
  if (isUniqueCharString(name))
   System.out.print("String is made up of unique chars");
  else
   System.out.print("String is not made up of unique chars");

 }

 //here we are using an integer as a bit vector....
 public static boolean isUniqueCharString(String temp) {
  int vector = 0;
  int val;
  for (int i = 0; i < temp.length(); i++) {
   val = temp.charAt(i) - 'a';
   if ((vector & (1 << val)) > 0)
    return false;
   vector = vector | (1 << val);
  }
  return true;
 }

 // Alternate solution - we can sort the characters of string and then
 // compare the neighbors
}

       
 

Friday, 6 May 2016

Find k closest elements in a sorted array using Java ......

here is the code .....


/*Given a sorted array arr[] and a value X, find the k closest elements to X in arr[].
 Examples:

 Input: K = 4, X = 35
 arr[] = {12, 16, 22, 30, 35, 39, 42,
 45, 48, 50, 53, 55, 56}
 Output: 30 39 42 45
 Note that if the element is present in array, then it should not be in output, only the other closest elements are required.
 */


       

public class FindKClosestElements {

 public static void main(String args[]) {

  int[] arr = {
   12,
   16,
   22,
   30,
   35,
   39,
   42,
   45,
   48,
   50,
   53,
   55,
   56
  };
  int element = 100;
  int k = 5;
  int m;
  int n;
  int distance1;
  int distance2;

  // case if element is is larger than even the last element in the array
  if (arr[arr.length - 1] < element) {
   n = arr.length - 1;
   while (k != 0) {
    System.out.print(arr[n]);
    System.out.print(" ");
    k--;
    n--;
   }
   return;
  }

  for (int i = 0; i < arr.length; i++) {
   if (arr[i] >= element) {
    m = i - 1;
    if (arr[i] == element)
     n = i + 1;
    else
     n = i;
    while (m >= 0 && n < arr.length && k != 0) {

     distance1 = arr[n] - element;
     distance2 = element - arr[m];

     if (distance1 <= distance2) {
      System.out.print(arr[n]);
      System.out.print(" ");
      k--;
      n++;
     } else {
      System.out.print(arr[m]);
      System.out.print(" ");
      k--;
      m--;
     }
    }
    if (k != 0) {
     if (m > 0)
      while (k != 0) {
       System.out.print(arr[m]);
       System.out.print(" ");
       m--;
       k--;
      } else
      while (k != 0) {
       System.out.print(arr[n]);
       System.out.print(" ");
       k--;
       n++;
      }
    }
    if (k == 0)
     return;
    else
     continue;
   }
  }
 }


}

       
 

Thursday, 5 May 2016

Merging two sorted arrays using Java ....

here is the code .....


       
public class MergingSortedLists {

 public static void main(String args[]) {

  int[] arr1 = {
   1,
   4,
   5,
   43,
   56,
   59
  };
  int[] arr2 = {
   2,
   3,
   6,
   34,
   36,
   42,
   67
  };
  int[] sortedList = new int[arr1.length + arr2.length];
  mergeLists(arr1, arr2, sortedList);
 }

 public static void mergeLists(int[] arr1, int[] arr2, int[] sortedList) {
  int k = 0;
  int j = 0;
  int t = 0;
  while (k < arr1.length && j < arr2.length) {
   if (arr1[k] <= arr2[j]) {
    sortedList[t] = arr1[k];
    t++;
    k++;
   } else {
    sortedList[t] = arr2[j];
    t++;
    j++;
   }
  }
  if (k != arr1.length) { //case where arr1 is left with elements not added to sorted list
   while (k < arr1.length) {
    sortedList[t] = arr1[k];
    t++;
    k++;
   }
  }
  if (j != arr2.length) { //case where arr2 is left with elements not added to sorted list
   while (j < arr2.length) {
    sortedList[t] = arr2[j];
    t++;
    j++;
   }
  }
  for (int s: sortedList) {
   System.out.print(s);
   System.out.print(" ");

  }
 }
}

       
 

Wednesday, 4 May 2016

Check whether two numbers are of opposite signs or not using Java .....

Problem -Two numbers are given ,you have to evaluate whether they are of opposite signs or not

Logic -Numbers are represented in 2's complemented form in computer where sign bit 0 means it is 
            positive number and 1 means it is negative .

here is the code ......


       
public class CheckOppositeSigns {

 public static void main(String args[]) {
  int x = 2;
  int y = -13;
  if (checkForOppositeSigns(x, y))
   System.out.print("Yes both the integers are of opposite signs");
  else
   System.out.print("Both the integers are of same sign");
 }

 public static boolean checkForOppositeSigns(int x, int y) {

  int signofFirstVariable = (x >> 31) ^ (0x1); //shifting the variable to place the sign bit at unit                                                                                     //position and then XOR with 000000000
  int signofSecondVariable = (y >> 31) ^ (0x1);
  if (signofFirstVariable != signofSecondVariable)
   return true;

  return false;
 }
}

       
 

Wednesday, 27 April 2016

Binary Search Tree implemented using Java ....

Binary Search Tree -

A binary search tree is a rooted binary tree, whose internal nodes each store a key (and optionally, an associated value) and each have two distinguished sub-trees, commonly denoted left and right. The tree additionally satisfies the binary search tree property, which states that the key in each node must be greater than all keys stored in the left sub-tree, and smaller than all keys in right sub-tree.[1]:287 (The leaves (final nodes) of the tree contain no key and have no structure to distinguish them from one another. Leaves are commonly represented by a special leaf or nil symbol, a NULL pointer, etc.)

here is the code ....



       
public class BinarySearchTreeImplementation {

 public static void main(String args[]) {

  BinarySearchTree tree = new BinarySearchTree();
  tree.addNode(50);
  tree.addNode(10);
  tree.addNode(100);
  tree.addNode(20);
  tree.addNode(200);
  tree.addNode(99);
  System.out.println("Binary Search Tree after the insertion of the nodes");
  tree.printBSTPreOrder();
 }

}

class BinarySearchTree {

 Node root;

 class Node {
  int data;
  Node leftChild;
  Node rightChild;

  Node(int d) {
   data = d;
   leftChild = null;
   rightChild = null;
  }
 }

 public void addNode(int d) {
  Node new_node = new Node(d);
  Node temp;
  if (root != null) {
   temp = root;
   Node parent_node = findPositionForNodeToAdd(temp, d);
   if (parent_node.data < d)
    parent_node.rightChild = new_node;
   else
    parent_node.leftChild = new_node;

  } else {
   root = new_node;
  }
 }

 public Node findPositionForNodeToAdd(Node root, int d) {

  if (root.leftChild == null && root.rightChild == null)
   return root;
  else if (root.data >= d) {
   if (root.leftChild != null)
    return findPositionForNodeToAdd(root.leftChild, d);
   else
    return root;
  } else if (root.data < d) {
   if (root.rightChild != null)
    return findPositionForNodeToAdd(root.rightChild, d);
   else
    return root;
  }

  return null;
 }

 //Prints the binary search tree in pre order traversal
 public void printBSTPreOrder() {
  if (root == null)
   System.out.println("Binary Search Tree is empty till now");
  else {
   Node temp = root;
   preOrder(temp);
  }
 }

 private void preOrder(Node root) {
  if (root == null)
   return;
  else {
   System.out.print(root.data + " ");
   preOrder(root.leftChild);
   preOrder(root.rightChild);
  }
 }
}