Sunday 17 July 2016

Factorial of a No. using Dynamic Programming

 Following program show how to find out the factorial of a No. using Dynamic Programming.

Factorial of No.   :
 
class Factorial
{
  public static void main(String[] args) {
    int n=8;
    long arr[] = new long[n+1];
    for(int i=0 ;i<n+1;i++)
      arr[i]=0L;
    System.out.println("Factorial is :: "+fact(n,arr));
  }
  static long fact(int n, long arr[])
  {
    if (n==0 || n==1)
      return 1;
    else if(arr[n]!=0)
      return arr[n];
    else
      {
        arr[n]=fact(n-1, arr)*n;
        return arr[n];
      }
  }
}

Friday 15 July 2016

Counting Sort

Following code show counting sort implementation in Java .

Counting Sort :   

class CountingSort
{
  public static void main(String[] args) {
    char arr[] = {'g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'};
    sort(arr);
    System.out.print("Sorted character array is ");
        for (int i=0; i<arr.length; ++i)
            System.out.print(arr[i]);
  }
  static void sort(char arr[])
  {
    int n = arr.length;
    int count[] = new int[256];
    for (int i=0; i<256; ++i)
        count[i] = 0;
    for (int i=0; i<n; ++i)
        ++count[arr[i]];
    for (int i = 0,j=0; i<n;j++)
      {  while(count[j]>0)
         {
           arr[i] = (char)j;
           --count[j];
           i++;
         }
      }
  }

}
 

Thursday 14 July 2016

Hackerrank , Project Euler #1: Multiples of 3 and 5

Here you can find solutions for  the famous Euler Project's Problems . Questions can find on following link https://www.hackerrank.com/contests/projecteuler/challenges.

 Project Euler #1: Multiples of 3 and 5     :

# Enter your code here. Read input from STDIN. Print output to STDOUT
t= input()
for i in range(0,t):
    no=input()
    n=(no-1)/3
    sum_3=(n*(2*3+3*(n-1))/2)
    n=(no-1)/5
    sum_5=(n*(2*5+5*(n-1))/2)
    n=(no-1)/15
    sum_15=(n*(2*15+15*(n-1))/2)
    print sum_3+sum_5-sum_15

Wednesday 13 July 2016

Selection Sort

Selection sort is a simple sorting algorithm.Smallest element is selected from the unsorted array and swapped with the leftmost element and that element becomes part of sorted array. This process continues moving unsorted array boundary by one element to the right.

 This algorithm is not suitable for large data sets as its average and worst case complexity are of O(n2) where n are no. of items.

Following  program shows selection sort algorithm in JAVA.

Selection Sort : 
public class SelectionSort {

    public static void main(String args[]) {
        int array[] = { 5, 2, 7, 4, 9, 0 };
        array = selectionSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
        }
    }

    private static int[] selectionSort(int array[]) {
        for (int i = 0; i < array.length; i++) {
            for (int j = i; j < array.length; j++) {
                if (array[i] > array[j]) {
                    int temp;
                    temp = array[j];
                    array[j] = array[i];
                    array[i] = temp;

                }
            }
        }
        return array;
    }

}

Tuesday 12 July 2016

BubbleSort

This Java bubble sort example shows how to sort an array of int using bubble sort algorithm. Bubble sort is the simplest sorting algorithm.

BubbleSort  :

package sorting;

public class BubbleSort {

    public static void main(String args[]) {
        int array[] = { 5, 2, 7, 4, 9, 0 };
        array = bubbleSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
        }
    }

    private static int[] bubbleSort(int array[]) {
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length - i - 1; j++) {
                if (array[j] > array[j + 1]) {
                    int temp;
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;

                }
            }
        }
        return array;
    }

}
 

QuickSort

Following program show Quicksort Algorithm in Java.

QuickSort:

public class QuickSort {
    public static void main(String args[]) {
        int array[]={9,2,5,1,7,1,2,9,5,4};
        quickSort(array,0,array.length-1);
        for(int e : array)
        {
            System.out.println(""+e);
        }
    }

    static void quickSort(int [] arr , int left ,int right)
    {
        if(left<right)
        {
        int p = partition(arr,left,right);
        quickSort(arr,left,p-1);
        quickSort(arr,p+1,right);
        }
    }

static int partition(int [] arr,int l, int h)
{
    int pivot=arr[h];
    int i=l-1;
    for(int j=l;j<h;j++)
    {
        if(arr[j]<=pivot)
        {
            swap(arr,i+1,j);
            i++;
        }
    }
swap(arr,i+1,h);
return i+1;
}
static void swap(int arr[] ,int i , int j)
{
    int temp= arr[i];
    arr[i]=arr[j];
    arr[j]=temp;
}

}

Monday 11 July 2016

Tower of Hanoi

Following Java program shows  demo of famous "Tower of Hanoi" Problem.

Tower of Hanoi     :

import java.util.*;
class TowerOfHonaoi
{

  public static void main(String[] args) {
    System.out.println("Enter No. of discs");
    Scanner sc = new Scanner(System.in);
    int no = sc.nextInt();
    move(no,"A","B","C");
  }

  public static void move(int n , String src, String inter, String dest)
  {
    if(n==1)
    {
        System.out.println(src+" -> "+dest);
    }else{
      move(n-1,src,dest,inter);
      System.out.println(src+" -> "+dest);
      move(n-1,inter,src,dest);
    }
  }

}

Wednesday 6 July 2016

Hackerrank , 30 Days of Code Challenges ( Day 28 & 29 Solution)

Day 28: RegEx, Patterns, and Intro to Databases  :

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int N = in.nextInt();
        for(int a0 = 0; a0 < N; a0++){
            String firstName = in.next();
            String emailID = in.next();
        }
    }
}

Day 29: Bitwise AND  :

import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int T = sc.nextInt();
        for (int tc = 0; tc < T; tc++) {
            int N = sc.nextInt();
            int K = sc.nextInt();

            System.out.println(solve(N, K));
        }

        sc.close();
    }

    static int solve(int N, int K) {
        int result = 0;
        for (int A = 1; A <= N; A++) {
            for (int B = A + 1; B <= N; B++) {
                int current = A & B;
                if (current > result && current < K) {
                    result = current;
                }
            }
        }
        return result;
    }
}

Hackerrank , 30 Days of Code Challenges ( Day 26th & 27th Solution)

 Day 26: Nested Logic :
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int actualDay = sc.nextInt();
        int actualMonth = sc.nextInt();
        int actualYear = sc.nextInt();
        int expectedDay = sc.nextInt();
        int expectedMonth = sc.nextInt();
        int expectedYear = sc.nextInt();

        int fine;
        if (actualYear > expectedYear) {
            fine = 10000;
        } else if (actualMonth > expectedMonth && (actualYear >= expectedYear)) {
            fine = 500 * (actualMonth - expectedMonth);
        } else if (actualDay > expectedDay && (actualMonth >= expectedMonth) && (actualYear >= expectedYear)) {
            fine = 15 * (actualDay - expectedDay);
        } else {
            fine = 0;
        }
        System.out.println(fine);

        sc.close();
    }
}

Day 27: Testing :

print "5"
print "4 3"
print "-1 0 4 2"
print "5 3"
print "0 1 -2 -6 9"
print "6 4"
print "1 0 -3 4 5 7"
print "7 5"
print "0 -3 -2 -1 6 -8 9"
print "8 6"
print "2 -4 5 1 3 7 6 0"

Hackerrank , 30 Days of Code Challenges ( Day 24 & 25 Solutions)

Day 24: More Linked Lists   :

public static Node removeDuplicates(Node head) {
     //Write your code here
       Node currentNode = head;
       while(currentNode!=null && currentNode.next!=null)
           {
           Node node = currentNode;
           while(node.next!=null)
               {
               if(node.next.data==currentNode.data)
                   {
                   Node next = node.next.next;
                   Node temp= node.next;
                   node.next=next;
                   temp=null;

               }
               else{
               node=node.next;
               }
           }
           currentNode=currentNode.next;
       }
       return head;
   }

Day 25: Running Time and Complexity  :

# Enter your code here. Read input from STDIN. Print output to STDOUT
import math
t=input()
def isPrime(data):
    if data < 2:
        return False
    v=int(math.sqrt(data))
    for i in range(2,v+1):
        if data%i==0:
            return False;
    return True;
for i in range(t):
    if isPrime(input()):
        print "Prime"
    else:
        print "Not prime"

   

Hackerrank , 30 Days of Code Challenges ( Day 21 - 23 Solutions)

Day 21: Generics  :
//Write your code here

static <E>  void printArray( E[] inputArray)
{
for( E e : inputArray)
    {
    System.out.println(""+e);
}

}

Day 22: Binary Search Trees  :

public static int getHeight(Node root){
    //Write your code here
      if(root ==null)
          return -1;
      int left=getHeight(root.left);
      int right=getHeight(root.right);
      return Math.max(left, right) + 1;
  }

Day 23: BST Level-Order Traversal   :

    static void levelOrder(Node root){
      //Write your code here
        Queue<Node> queue = new LinkedList<Node>();
        queue.add(root);
        while(queue.peek()!=null)
            {
            Node node =queue.remove();
            System.out.print(""+node.data+" ");
            if(node.left!=null)
                queue.add(node.left);
            if(node.right!=null)
                queue.add(node.right);
        }
    }