Sunday, February 10, 2013

Matrix sorting by row wise



class Sort_Matrix{
public static void main (String args[]){
 int [][] M ={ {1,2,3,4},{2,3,4,5},
                      {5,6,7,8},{6,7,8,5},{3,7,9,3} };
 for(int r=0;r<5;r++){
   for(int c=0;c<4;c++){
     System.out.print(M[r][c]+"\t ");
    }
   System.out.println();
  }
  for(int r=0;r<5;r++){
  int maxEle=M[r][0];
   for(int c=1;c<4;c++){
   if(M[r][c]>maxEle){
    int temp=maxEle;
    maxEle=M[r][c];
    M[r][c]=temp;
    }
   }
   System.out.println(
"Maximum row "+(r+1)+"element is= "+maxEle);
   }
  }
}

Addition of Two matrix


we are going to calculate the sum of two matrix and containing its rows and columns. See below for better understanding to this: 
In this program we are going to calculate the sum of two matrix. To make this program, we need to declare two dimensional array of type integer.
Now we need to make a matrix out of it. To make the matrix we will use the for loop. By making use of the for loop the rows and column will get divide. This process will be performed again for creating the second matrix. After getting both the matrix with us, we need to sum both the matrix. The both matrix will be added by using the for loop with C[r][c]= A[r][c]+B[r][c]. The output will be displayed by using the print() method.


public class addMatrix{
      int A[][];
      int B[][];
      int C[][];
      int row;
      int column;

public addMatrix(int r,int c){
row=r;
column=c;
      A=new int[r][c];
      B=new int[r][c];
      C=new int[r][c];

for(int i=0;i<r;i++){
    for(int j=0;j<c;j++){

A[i][j]=(int) Math.round(Math.random()*99+10);
B[i][j]=(int) Math.round(Math.random()*70+10);
}

}
}
public void addition(){
for(int i=0;i<row;i++){
   for(int j=0;j<column;j++){

C[i][j]=A[i][j]+B[i][j];
}
}
}
public void display(){

for(int i=0;i<row;i++){
  for(int j=0;j<column;j++){

System.out.print(C[i][j]+"\t");
}
System.out.println();
}

}

public static void main(String args[]){
addMatrix m=new addMatrix(4,5);
m.addition();
m.display();
}
}

Output is:

C:\Users\Hari\Desktop\java>java addMatrix
134     88      115     87      161
65      188     52      166     98
86      83      43      106     93
62      104     100     49      159


similarly substraction as given


Subtraction of two matrix in java

we are going to calculate the subtraction of two matrix and containing its rows and columns. See below for better understanding to this: 
In this program we are going to calculate the  subtraction  of two matrix. To make this program, we need to declare two dimensional array of type integer. Now we need to make a matrix out of it. To make the matrix we will use the for loop.
By making use of the for loop the rows and column will get divide. This process will be performed again for creating the second matrix. After getting both the matrix with us, we need to subtraction  both the matrix. The both matrix will be subtracted by using the for loop with C[r][c]= A[r][c]-B[r][c]. The output will be displayed by using the print() method.

Creating a Matrix


In this example  you will learn about array and matrix. An array is the collection of same data type values. If we create a variable of integer type then, the array of int can only store the int values. It can't store other than int data type.
Matrix: A matrix is a collection of data in rows and columns format.
In this program we are going to implement a matrix. To make a program over the two dimensional array,list of all we have to declare class named as 
Matrix , For displaying the matrix we need to its rows and column . Now, we use the for loop to print all the values stored in the array. At last use the main() method inside which we are going to declare the values of the multidimensional array which we are going to use.  The output will be displayed to the user by print() ,println() methods.





public class createMatrix{
    public static void main(String args[]){
              int Matrix[][]={{1,4,5,6},{2,4,5,6},{5,6,8,9},{2,4,7,9}};

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



or


public class createMatrix{
    public static void main(String args[]){
              int Matrix[][]=new int[4][4];

for(int i=0;i<4;i++){
     for(int j=0;j<4;j++){

Matrix[i][j]=(int) Math.round(Math.random()*89+11);
       System.out.print(Matrix[i][j]+"\t");
}
System.out.println();
}
}
}       



output for 1:
C:\Users\Hari\Desktop\java>java createMatrix
1       4       5       6
2       4       5       6
5       6       8       9
2       4       7       9


output for 2:
C:\Users\Hari\Desktop\java>java createMatrix
1       4       5       6
2       4       5       6
5       6       8       9
2       4       7       9
  

Thursday, February 7, 2013

N Queen Problem

public class NQueens { 
  
    int[] x; 
  
    public NQueens(int N) { 
        x = new int[N]; 

    } 
  
    public boolean canPlaceQueen(int r, int c) { 
       
        for (int i = 0; i < r; i++) { 
            if (x[i] == c || (Math.abs(i - r) == Math.abs(x[i] - c)) )  
            { 
                return false; 
            } 
        } 
        return true; 
    } 
  
    public void printQueens(int[] x) { 
        int N = x.length; 
        for (int i = 0; i < N; i++) { 
            for (int j = 0; j < N; j++) { 
                if (x[i] == j) { 
                    System.out.print("Q "); 
                } else { 
                    System.out.print("* "); 
                } 
            } 
            System.out.println(); 
        } 
        System.out.println(); 
    } 
  
    public void placeNqueens(int r, int n) { 
        
        for (int c = 0; c < n; c++) { 
            if (canPlaceQueen(r, c)) { 
                x[r] = c; 
                if (r == n - 1) { 
                   printQueens(x); 
                } else { 
                    placeNqueens(r + 1, n); 
                } 
            } 
        } 
    } 
  
    public void callplaceNqueens() { 
        placeNqueens(0, x.length); 
    } 
  
    public static void main(String args[]) { 
        NQueens Q = new NQueens(5); 
        Q.callplaceNqueens(); 

       
    } 
}

Linear Search

import javax.swing.*;
public class LinearSearch{
    int [] array;
int n;
   
   
    public LinearSearch(int n){
        this.n = n;
        array = new int[n];
        for(int i = 0; i< n; i++){
            array[i]=getRandom(0,2*n);
        }
    }
   
    public int search(int key){
        int index=0;
        while (index < n && key!=array[index]) index++;
       
        if (index==n) return -1;
        return index;
    }
   
    public static int getRandom(int from, int to){
        return (int)Math.round(Math.random()*(to-from)+from);
    }

public void shortarray(int arraySize){
int temp=0;
for(int i=0;i<arraySize;i++){
for(int j=i;j<arraySize;j++){
if(array[i]>array[j]){
temp=array[i];
array[i]=array[j];
array[j]=temp;
}
}
}
/*System.out.println();

for(int i=0;i<2000;i++){
System.out.print(array[i]+" ");
}*/
}


     public static void main(String args[]){
        int arraySize=2000;
 LinearSearch ls = new LinearSearch(arraySize);

 ls.shortarray(arraySize);

        for(int repeat=0; repeat< 100; repeat++){
    int numberOfTries=5000;
            int key, result;
            int successCount=0;
            int failureCount=0;
            int averageComparisonForSuccess=0;
            for(int i=0; i< numberOfTries; i++){
                key=ls.getRandom(0,2*arraySize);
                result=ls.search(key);
               
                if (result==-1) failureCount++;
                else{successCount++;
                    averageComparisonForSuccess+=result+1;
                }
            }
            if (successCount>0) averageComparisonForSuccess=averageComparisonForSuccess/successCount;
            String analysisResult="---Search Analysis Report "+(repeat+1)+"---\n"+
            "Array Size="+ls.array.length+
            "\nNumber of Tries="+numberOfTries+
            "\nSuccessfull Searches="+successCount+"\n"+
            "Unsuccessfull Searches="+failureCount+"\n"+
            "Average Count of Comparisons in Successfull Searches="+ averageComparisonForSuccess+
            "\n---End of Report--\n";
           
          
     
            System.out.println(analysisResult);

        }

    }


}

Finding Max and Min

public class MaxMin {
int [] array;
int n,max,min;
public MaxMin(int n){
    this.n=n;
    array=new int[n];
    for(int i=0;i<n;i++){
        array[i]=(int) Math.round(Math.random()*22+1000);
    }
}
public void findmaxmin(){
    max=array[0];
    min=array[0];
    for(int i=0;i<n;i++){
        if(array[i]<min)min=array[i];
        else if(array[i]>max)max=array[i];
       
    }
  }
    public void print(){
        findmaxmin();
        for(int i=0;i<n;i++){
            System.out.print(array[i]+" ");

        }
        System.out.println();
        System.out.println("max = "+max);
        System.out.print("min = "+min);
    }
    public static void main(String[] a){
        MaxMin s1=new MaxMin(10);
        s1.print();
    }
}

Binary Search

public class BSearch {
    int [] array={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
    int n;
    int key;
  public BSearch(){
      //this.key=key;
     // array={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
      n=array.length;

  }
  public int serch(int key){
     return serch(key,0,n-1);
  }

    public int serch(int key,int s, int e) {
        int mid=(s+e)/2;
       if(e<s){return -1;}
      
       else if(key==array[mid]){return mid;}

        else if(key<array[mid]){return serch(key,s,mid-1);}
    else{return serch(key,mid+1,e);}
    }
public void print(int key){
    System.out.println("index of "+key+"  =   "+serch(key));
  
}
public static void main(String[] a){
BSearch s1=new BSearch();
s1.print(20);
}
}

palindrome

public class Stack{
private Object element[];
private int top;
int maxSize;
private String x,y;

public Stack(int s,String x){
maxSize=s;
element=new Object[maxSize];
top=-1;
this.x=x;
y="";
}

public boolean isEmpty(){
return(top==-1);
}

public void push(Object elt){
top=top+1;
element[top]=elt;
}

public Object pop(){
Object e=element[top];
top=top-1;
return e;
}

public Object peek(){
return element[top];
}

public void change(){

for(int i=0;i<x.length();i++){
push(x.charAt(i));
}
}

public void set(){
while(!isEmpty()){
y=y+pop();
}
System.out.println(y);

}

public boolean eguals(){
return(x.compareTo(y)==0);
}

public static void main(String a[]){
Stack s=new Stack(5,"amma");
s.change();
s.set();
System.out.println("palindrome  "+s.eguals());

Stack s2=new Stack(5,"ammaa");
s2.change();
s2.set();
System.out.println("palindrome  "+s2.eguals());
}
}

Quick Sort

public class QuickSort {
    int[] num;
    int n;
    public QuickSort(int n){
        this.n=n;
       // p=0;q=n;
        num=new int[n+1];
        for(int i=0;i<n;i++){
            num[i]= (int) Math.round(Math.random()*n/2+1000);

        }
        num[n]=99999;
       // quickSort(0,n-1);
    }
    public void quickSort(){
     quickSort(0,n-1);
    }
 public void quickSort(int p,int q){
     int j;
     if(p<q){
            j=partition(p,q);
                quickSort(p,j-1);
                quickSort(j+1,q);

     }
 }

    private int partition(int p, int q) {
       int i=p;
       int j=q+1;
       int pivot=num[p];
       do{
           do{ i++;
           }while(num[i]<pivot);
        do{j--;
       }while(num[j]>pivot);
 
         if(i<j){
             swap(i,j);}
         }while(i<j);
       swap(p,j);
     
   
     return j;
}

    private void swap(int i, int i0){
        int temp=num[i];
        num[i]=num[i0];
        num[i0]=temp;
    }
    public void print(){
     
     
        for(int i=0;i<n;i++){
            System.out.print(num[i]+" ");
        }
    }
 
 public static void main(String []a){
      QuickSort s=new QuickSort(100);
       System.out.println("Before Sort");
       s.print();
       s.quickSort();
       System.out.println();
       System.out.println("after Sort");
       s.print();
 }
}

Merge Sort

public class MergeSort {
    int[] array;
    int size;
   public MergeSort(int size){
              array=new int[size];
       for(int i=0;i<size;i++){
           array[i]=(int) Math.round(Math.random()*900+100);
       }
   }
   public void mergesort(){
       mergesort(0,size-1);
   }
   public void mergesort(int l,int r){
       if(l<r){
           int mid=(l+r)/2;
           mergesort(l,mid);
           mergesort(mid+1,r);
           merge(l,mid,r);
       }
   }

    private void merge(int l, int m, int r) {
       int i=l; int j=m+1; int k=0;
       int[] temp=new int[r-l+1];
       while(i<=m && j<=r){
           if(array[i]>array[j])temp[k++]=array[i++];
           else temp[k++]=array[j++];
       }
       while(i<=m) temp[k++]=array[i++];
       while(j<=r) temp[k++]=array[j++];
       for(k=0;k<r-l+1;k++) array[l+k]=temp[k];
    }
public void display(){
    int psize=15;
    String ds="";
    int rows=(size-1)/psize+1;
    int k=0;
    int i,row;
            for(row=1;row<rows;row++){
                for(i=0;i<psize;i++)
                    ds=ds+" : "+array[k++];
                    ds=ds+"\n";

            }
    for(i=k;i<size;i++)ds=ds+" : "+array[i];
    JOptionPane.showMessageDialog(null,ds,"contents of the array",1);
    System.out.print(ds);
}
public static void main(String[] a){
     MergeSort s1=new  MergeSort(20);
     System.out.println("Before Sort");
     s1.display();
     System.out.println();
     s1.mergesort();
     System.out.println("After Sort");
     s1.display();
}
}