Search This Blog

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

Wednesday, 22 March 2017

Implement Candidate Elimination Algorithm in JAVA

Program:
package k;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class kl {
                static int sg = 0;

Thursday, 16 March 2017

Program in JAVA to implement Mutual Exclusion.

public class Counter_locks implements Runnable {

      int count = 0;

     public Counter_locks() { 
     }

     public synchronized void run()  //synchronizes the run method
     {
         System.out.println(Thread.currentThread().getName() + ": " + "Current Value of count = " + count);
         System.out.println(Thread.currentThread().getName() + " increments count....");
         count ++;
        try {
                             Thread.currentThread().sleep(1000);
         } catch (InterruptedException e) {
             System.out.println("Thread " + Thread.currentThread().getName() + "interrupted.");
         }
         System.out.println("Value of count after incremented by thread "
         + Thread.currentThread().getName() + " = " + count);
     }

     public static void main(String args[]) {
         Counter_locks c = new Counter_locks();
  
         Thread t1 = new Thread(c);
         Thread t2 = new Thread(c);
         Thread t3 = new Thread(c);
         Thread t4 = new Thread(c);
  
         t1.setName("Thread 1");
         t2.setName("Thread 2");
         t3.setName("Thread 3");
         t4.setName("Thread 4");
  
         t1.start();
         t2.start();
         t3.start();
         t4.start();
  
         try {
             t1.join();
             t2.join();
             t3.join();
             t4.join();
         }
         catch (InterruptedException e) {
             System.out.println("Main thread Interrupted .....");
         }
  
         System.out.println("Main thread exits.....");
     }
 }

Output :

D:\>javac  Counter_locks.java
D:\>java Counter_locks
Thread 1: Current Value of count = 0
Thread 1 increments count....
Value of count after incremented by thread Thread 1 = 1
Thread 4: Current Value of count = 1
Thread 4 increments count....
Value of count after incremented by thread Thread 4 = 2
Thread 3: Current Value of count = 2
Thread 3 increments count....
Value of count after incremented by thread Thread 3 = 3
Thread 2: Current Value of count = 3
Thread 2 increments count....
Value of count after incremented by thread Thread 2 = 4

Main thread exits.....

Wednesday, 15 March 2017

DeadlockAvoidance (java)

import java.util.Scanner;
public class DeadlockAvoidance{
 private int need[][],allocate[][],max[][],avail[][],np,nr;
  private void input() {  
   Scanner sc=new Scanner(System.in);
     System.out.print("Enter no. of processes and resources : ");
     np=sc.nextInt();  //no. of process
     nr=sc.nextInt();  //no. of resources
     need=new int[np][nr];  //initializing arrays
     max=new int[np][nr];
     allocate=new int[np][nr];
     avail=new int[1][nr];
         System.out.println("Enter allocation matrix -->");
     for(int i=0;i<np;i++)
          for(int j=0;j<nr;j++)
         allocate[i][j]=sc.nextInt();  //allocation matrix
            System.out.println("Enter max matrix -->");
     for(int i=0;i<np;i++)
          for(int j=0;j<nr;j++)
         max[i][j]=sc.nextInt();  //max matrix
               System.out.println("Enter available matrix -->");
        for(int j=0;j<nr;j++)
         avail[0][j]=sc.nextInt();  //available matrix
            sc.close(); }
    private int[][] calc_need(){
       for(int i=0;i<np;i++)
         for(int j=0;j<nr;j++)  //calculating need matrix
          need[i][j]=max[i][j]-allocate[i][j];
           return need;
    }
      private boolean check(int i){
       //checking if all resources for ith process can be allocated
       for(int j=0;j<nr;j++)
       if(avail[0][j]<need[i][j])
          return false;
        return true;
    }
    public void isSafe(){
       input();
       calc_need();
       boolean done[]=new boolean[np];
       int j=0;
       while(j<np){  //until all process allocated
       boolean allocated=false;
       for(int i=0;i<np;i++)
        if(!done[i] && check(i)){  //trying to allocate
            for(int k=0;k<nr;k++)
            avail[0][k]=avail[0][k]-need[i][k]+max[i][k];
         System.out.println("Allocated process : "+i);
         allocated=done[i]=true;
               j++;  }
          if(!allocated) break;  //if no allocation
       }
       if(j==np)  //if all processes are allocated
        System.out.println("\nSafely allocated");
       else
        System.out.println("All proceess cant be allocated safely");    }
      public static void main(String[] args) {
       new DeadlockAvoidance().isSafe();
    }}

Monday, 6 March 2017

Java Program to Implement Candidate Elimination Algorithm.

/*Java Program to Implement Candidate Elimination  Algorithm.*/

import java.io.BufferedReader;
import java.io.FileReader;
public class CandidateElimination {
                public static void main(String[] args) throws Exception{
                                // Calculating input space
                                int inputSpace= (int)Math.pow(2,4); //2^x
                                System.out.println(inputSpace);
                                // Calculating hypothesis space
                                int hypothesisSpace= (int)Math.pow(2,inputSpace);
                                System.out.println(hypothesisSpace);
                                // Initializations
                                int j,high,low;
                                String row;
                                String[] Attributes = new String[10];
                                // Getting number of digits required for the array
                                int num_digits=(int)(Math.log(hypothesisSpace)/Math.log(2));
                                /* Initializing conceptSpace array for the problem. Adding a
                                 * column for flag to check for deleted rows.
                                 */
                                int[][] conceptSpace = new int[hypothesisSpace][num_digits+1];
                                int[][] versionSpace;
                                // Readers for reading input files
                                BufferedReader br = null;
                                BufferedReader btest = null;
                                /* Populating the conceptSpace array for all possible
                                 * combinations. Using binary filling to represent all
                                 * hypothesises in concept space.
                                 */
                                for(int i=0;i<hypothesisSpace;i++)
                                { j=num_digits;
                                                int temp=i;
                                                while(temp>=0&&j>0) {
                                                                j--;
                                                                if(temp%2==1)
                                                                                conceptSpace[i][j]=1;
                                                                else
                                                                                conceptSpace[i][j]=0;
                                                                temp=temp/2; }
                                                conceptSpace[i][num_digits]=1;  }
                                // Connecting the buffers to the actual file
                                Try {
                                                br = new BufferedReader(new FileReader("4Cat-Train.labeled"));
                                                btest = new BufferedReader(new FileReader(args[0]));  }
                                catch(Exception e) {
                                                e.printStackTrace();
                                                return; }
                             /* temp will store current attribute value, input stores the number
                                 * to check in a specific column of the concept space. result stores
                                 * the given output from the file.
                                 */
                                int temp=0,input,result;
                               
                                /*
                                 *  Obtaining the version space from concept space by using
                                 *  LIST-THEN-ELIMINATE algorithm.
                                 */
                                while((row=br.readLine())!=null)
                                {             
                                                input=0;
                                                if(!row.equals("\n"))
                                                {
                                                                // Splitting based on spaces and tabs
                                                                Attributes = row.split("\\s+");
                                                                // Every alternate value is an attribute
                                                                if(Attributes[1].equals("Male"))
                                                                                temp=1;
                                                                else
                                                                                temp=0;
                                                                input=temp;
                                                                if(Attributes[3].equals("Old"))
                                                                                temp=1;
                                                                else
                                                                                temp=0;
                                                                input=input*2+temp;
                                                                if(Attributes[5].equals("Yes"))
                                                                                temp= 1;
                                                                else
                                                                                temp=0;
                                                                input=(input*2)+temp;
                                                                if(Attributes[7].equals("Yes"))
                                                                                temp= 1;
                                                                else
                                                                                temp=0;
                                                                input=input*2+temp;
                                                                //Get actual result
                                                                if(Attributes[7].equals("high"))
                                                                                result=1;
                                                                else
                                                                                result=0;
                                                                // Check for the same input in conceptSpace
                                                                for(int i=0;i<hypothesisSpace;i++)
                                                                {              // Check only if it a valid row
                                                                                if(conceptSpace[i][num_digits]==1)
                                                                                {
                                                                                                if(conceptSpace[i][input]!=result)
                                                                                                {
                                                                                                                // If it does not match change the flag
                                                                                                                conceptSpace[i][num_digits]=0;
                                                                                }}}}}
                               
                                //Counting Valid Hypothesis
                                int count=0;
                                for(int i=0;i<hypothesisSpace;i++)
                                {              // The rows that still have flag as 1 are valid
                                                if(conceptSpace[i][num_digits]==1)
                                                {
                                                                count++;
                                                }
                                }
                                //CREATE Version Space
                                System.out.println(count);
                                versionSpace = new int[count][num_digits];
                                temp=0;
                                for(int i=0;i<hypothesisSpace;i++)
                                {
                                                if(conceptSpace[i][num_digits]==1)
                                                {
                                                                /* Copying from conceptSpace to version to increase performance
                                                                 * Traversing an 65536 for a few valid hypothesis wastes a lot
                                                                 * of processing capability
                                                                 */
                                                                for(j=0;j<num_digits;j++)
                                                                                versionSpace[temp][j]=conceptSpace[i][j];
                                                                temp++;
                                                }
                                }

                                //Testing on input set, file passed through argument to program
                                while((row=btest.readLine())!=null)
                                {
                                                input=0;
                                                if(!row.equals("\n"))
                                                {
                                                                high=low=0;
                                                                Attributes = row.split("\\s+");
                                                                if(Attributes[1].equals("Male"))
                                                                                temp=1;
                                                                else
                                                                                temp=0;
                                                                input=temp;
                                                                if(Attributes[3].equals("Old"))
                                                                                temp=1;
                                                                else
                                                                                temp=0;
                                                                input=input*2+temp;
                                                                if(Attributes[5].equals("Yes"))
                                                                                temp= 1;
                                                                else
                                                                                temp=0;
                                                                input=(input*2)+temp;
                                                                if(Attributes[7].equals("Yes"))
                                                                                temp= 1;
                                                                else
                                                                                temp=0;
                                                                input=input*2+temp;
                                                                for(int i=0;i<count;i++)
                                                                {
                                                                                //Checking the input in versionSpace
                                                                                if(versionSpace[i][input]==1)
                                                                                                high++;
                                                                                else
                                                                                                low++;                 
                                                                }
                                                                //Print number of high and low votes
                                                                System.out.println(high+" "+low);
                                                }
                                }
                                // Closing opened files
                                try
                                {
                                                br.close();
                                                btest.close();
                                }catch(Exception e)
                                {
                                                e.printStackTrace();
} }}


OUTPUT:-

D:\DemoJava>javac CandidateElimination.java
D:\DemoJava>java CandidateElimination
16
65536
java.io.FileNotFoundException: 4Cat-Train.labeled (The system cannot find the fi
le specified)
        at java.io.FileInputStream.open0(Native Method)
        at java.io.FileInputStream.open(FileInputStream.java:195)
        at java.io.FileInputStream.<init>(FileInputStream.java:138)
        at java.io.FileInputStream.<init>(FileInputStream.java:93)
        at java.io.FileReader.<init>(FileReader.java:58)
        at CandidateElimination.main(CandidateElimination.java:49)