Monday, 11 August 2014

Banker's Algorithm For Deadlock Avoidance

/*
 * Data structures used for Banker's Algorithm
 */
/*
 * Let the number of Processes be n and number of different resources be m.
 * Then...
 *
 * available: A vector of length m indicates the number of available resources
                           of each type. If available[j] = k, there are k instances of resource type Rj are
                           available.
 */
/*
 * max:              An n x m matrix defines the maximum demand of each process. If
                           max[i,j] = k, then process Pi may request at most k instances of resource type
                           Ri.
 */

/*
 * allocation:       An n x m matrix defines the number of resources of each type
                           currently allocated to each process. If allocation[i,j] = k, then process Pi is
                           currently allocated k instances of resource type Rj.
 */

/*
 * need:             An n x m matrix indicates the remaining resource need of each
                           process. If need[i,j] = k, then process Pi may need k more instances of
                           resource type Ri to complete its task. Note that need[i,j] = max[i,j] -
                           allocafion[i,j].
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class Main
{
       static String safetySequence=new String("");
       static int n,m,available[],max[][],allocation[][],need[][],request[],resources[];
      
       public static void main(String args[]) throws NumberFormatException, IOException
       {
              BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
             
              System.out.print("Enter the number of Processes : ");
              n=Integer.parseInt(br.readLine());
             
              System.out.print("Enter the number of Resources : ");
              m=Integer.parseInt(br.readLine());
             
              /*
               * defining the data structures used in Banker's Algorithm
               */
              available=new int[m];
              max=new int[n][m];
              allocation=new int[n][m];
              need=new int[n][m];
              request=new int[m];
              resources=new int[m];
             

              /*
               * taking the input for the maximum of resources.
               */
              System.out.println("Enter the number maximum number of instances available for each resource ");
              for(int i=0;i<m;i++)
              {
                     System.out.print("Enter the maximum number of instances of resource "+(i+1)+" : ");
                     resources[i]=Integer.parseInt(br.readLine());
              }
                    
              /*
               * taking the input for the maximum of resources needed by all the jobs.
               */
              System.out.println("Enter the data for the max array : ");
              for(int i=0;i<n;i++)
              {
                     for(int j=0;j<m;j++)
                     {
                           System.out.print("Enter the maximum instances needed by the process number : "+(i+1)+" of resource number "+(j+1)+" :");
                           max[i][j]=Integer.parseInt(br.readLine());
                     }
              }
              /*
               * taking the input for filling the allocation of resources needed by all the job
               */
              System.out.println("Enter the data for the allocation array : ");
              for(int i=0;i<n;i++)
              {
                     for(int j=0;j<m;j++)
                     {
                           System.out.print("Enter the allocated instances to the process number : "+(i+1)+" of resource number "+(j+1)+" :");
                           allocation[i][j]=Integer.parseInt(br.readLine());
                     }
              }
             
              calculateAvailableArray();
              calculateNeedArray();
             
              /*
               * taking the input for the request array
               * that will be needed by a particular process
               */
             
              System.out.print("Enter the process number for which you will be entering the request array : ");
              int processNumber=Integer.parseInt(br.readLine())-1;
             
              System.out.println("Enter the data for request array for process "+(processNumber+1)+" : ");
              for(int i=0;i<m;i++)
              {
                     System.out.print("Enter the number of instances requested for resource "+(i+1)+" : ");
                     request[i]=Integer.parseInt(br.readLine());
              }
             
              /*
               * Actual Banker's Algorithm starts here
               */
             
              /*
               * Banker's algorithm is divided into two sub-algorithms :
               *     1. Resource Allocation Algorithm
               *     2. Safety Algorithm
               */
             
              /*
               * Resource Allocation Algorithm starts here :
               */
             
              /*
               * step 1. The request of this particular process should be less than the need of this process.
               */
              boolean isAllocationPossible=true;
              for(int i=0;i<m;i++)
              {
                     if(request[i]>need[processNumber][i])
                     {
                           isAllocationPossible=false;
                           break;
                     }
              }
              /*
               * step 2. The request of this particular process should be less than the available instances of this process.
               */
             
              for(int i=0;i<m;i++)
              {
                     if(request[i]>available[i])
                     {
                           isAllocationPossible=false;
                           break;
                     }
              }
              if(isAllocationPossible)
              {
                     /*
                      * if allocation is possible then go to step 3.
                      * step 3 is as follows :
                      */
                    
                     /*
                      * making a clone of available, allocation and need
                      * so than we can roll back if the requested instances of resources leaves the system in deadlocked state.
                      */
                    
                     int availableClone[]=available.clone();
                     int allocationClone[][]=allocation.clone();
                     int needClone[][]=need.clone();
                    
                     /*
                      * making the system to pretend as if the request has been granted...
                      */
                     for(int i=0;i<m;i++)
                     {
                           available[i]=available[i]-request[i];
                     }
                     for(int i=0;i<m;i++)
                     {
                           allocation[processNumber][i]+=request[i];
                     }
                     for(int i=0;i<m;i++)
                     {
                           need[processNumber][i]-=request[i];
                     }
                    
                     if(!isSystemInSafeState())
                     {
                           System.out.println("The requested instances of the resources not allocated successfully as they don't leave the system in a safe state.");
                           available=availableClone;
                           allocation=allocationClone;
                           need=needClone;
                     }
                     else
                     {
                           System.out.println("The requested instances of the resources are allocated successfully.");
                           System.out.println("\nThe Safety Sequence is : \n"+safetySequence);
                           System.out.println("The new state of the system is :");
                           for(int i=0;i<n;i++)
                           {
                                  System.out.print("P"+(i+1)+" -> ");
                                  for(int j=0;j<m;j++)
                                  {
                                         System.out.print(allocation[i][j]+" ");
                                  }
                                  System.out.println();
                           }
                     }
              }
              else
              {
                     System.out.println("The Requested instances of the resources can't be allocated.");
              }
       }     
      
       public static boolean isSystemInSafeState()
       {
              /*
               * this method contains the implementation of the safety algorithm
               */
              int work[]=available.clone();
              boolean finish[]=new boolean[n];
              for(int i=0;i<finish.length;i++)
              {
                     finish[i]=false;
              }
              /*
               * step 2 starts here
               */
              while(true)
              {
                     int i;
                     for(i=0;i<n;i++)
                     {
                           int counter=0;
                           for(int j=0;j<m;j++)
                           {
                                  if(need[i][j]<=work[j])
                                  {
                                         counter++;
                                  }
                           }
                           if(counter==m && !finish[i])
                           {
                                  break;
                           }
                     }
                    
                     if(i==n)
                     {
                           int count=0;
                           for(int j=0;j<n;j++)
                           {
                                  if(finish[j])
                                         count++;
                           }
                           if(count==n)
                                  return true;
                           else
                                  return false;
                     }
                    
                     finish[i]=true;
                     safetySequence+=("P"+(i+1)+"  ");
                    
                     for(int j=0;j<m;j++)
                     {
                           work[j]+=allocation[i][j];
                     }
              }     
       }
       public static void calculateNeedArray()
       {
              /*
               * calculating the data of need array :
               */
             
              for(int i=0;i<n;i++)
              {
                     for(int j=0;j<m;j++)
                     {
                           need[i][j]=max[i][j]-allocation[i][j];
                     }
              }
             
       }
       public static void calculateAvailableArray()
       {
              /*
               * calculating the data of the available array :
               */
             
              for(int i=0;i<m;i++)
              {
                     for(int j=0;j<n;j++)
                     {
                           available[i]+=allocation[j][i];
                     }
              }
              for(int i=0;i<m;i++)
              {
                     available[i]=resources[i]-available[i];
              }
       }
}

Wednesday, 25 June 2014

Forgot Password-Solution


Problem Statement:

Chef changed the password of his laptop a few days ago, but he can't remember it today. Luckily, he wrote the encrypted password on a piece of paper, along with the rules for decryption.
The encrypted password is a string S consists of ASCII printable characters except space (ASCII 33 - 126, in decimal notation, the same below). Read here for more details: ASCII printable characters.
Each rule contains a pair of characters ci, pi, denoting that every character ci appears in the encrypted password should be replaced with pi. Notice that it is not allowed to do multiple replacements on a single position, see example case 1 for clarification.
After all the character replacements, the string is guaranteed to be a positive decimal number. The shortest notation of this number is the real password. To get the shortest notation, we should delete all the unnecessary leading and trailing zeros. If the number contains only non-zero fractional part, the integral part should be omitted (the shortest notation of "0.5" is ".5"). If the number contains zero fractional part, the decimal point should be omitted as well (the shortest notation of "5.00" is "5").
Please help Chef to find the real password.

Input

The first line of the input contains an interger T denoting the number of test cases.
The description of T test cases follows.
The first line of each test case contains a single interger N, denoting the number of rules.
Each of the next N lines contains two space-separated characters ci and pi,
denoting a rule.
The next line contains a string S, denoting the encrypted password.

Output

For each test case, output a single line containing the real password.

Constraints

  • 1 ≤ T ≤ 1000
  • 0 ≤ N ≤ 94
  • All characters in S and ci may be any ASCII printable character except space. (ASCII 33 - 126)
  • All ci in a single test case are distinct.
  • pi is a digit ("0" - "9") or a decimal point "." (ASCII 46).
  • The total length of S in a single input file will not exceed 106.

Example

Input:
4
2
5 3
3 1
5
0
01800.00
0
0.00100
3
x 0
d 3
# .
0xd21#dd098x

Output:
3
1800
.001
321.33098 
 
 
Solution:
 
/*******************************************************************************************/
 
 
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
 int t,n,i,ch,flag,flag1;
 int j,k,l;
 char ci,pi,*str,*cih;
 scanf("%d",&t);
 cih=(char*)malloc(sizeof(char)*130);
  
 for(i=0;i<t;i++)
 { 
  str=(char*)malloc(sizeof(char)*10000000);
 
  flag=0;
  flag1=0;
  for(j=0;j<130;j++)
   cih[j]=' ';
  scanf("%d",&n);
  for(j=0;j<n;j++)
  {
   scanf(" %c %c",&ci,&pi);
   ch=(int)ci;
   cih[ch]=pi;
  }
  
  scanf("%s",str);
  
  for(j=0;str[j]!='\0';j++)
  {
   if(cih[(int)str[j]]!=' ')
    str[j]=cih[(int)str[j]];
  }
  
  for(j=0;str[j]!='\0';j++)
  {
   if(str[j]=='0' || str[j]=='.')
   { 
   }
   else
   {
    flag1=1;
    break;
   }
  }
  
  if(flag1==1)
  {
   for(j=0;str[j]!='\0';j++)
   {
    if(str[j]!='0')
     break;
   }
  
   for(k=j;str[k]!='\0';k++)
   {
    if(str[k]=='.')
    {
     flag=1;
     break;
    } 
   }
   k=strlen(str)-1;
   if(flag==1)
   {
    for(k=(strlen(str)-1);k>=j;k--)
    {
     if(str[k]!='0')
      break;
    }
    if(str[k]=='.')
     k=k-1;
   }
  
   for(l=j;l<=k;l++)
    printf("%c",str[l]);
   printf("\n");
  }
  else
   printf("0\n"); 
  free(str);
 }
 return 0;
} 


/*************************************************************************************/

Tuesday, 10 June 2014

Simple Program to record Sound and play them back - Source Code - Java

Download the Source code from here.
View the eclipse project here.
/*****************************************************************************/
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.JButton;
import javax.swing.JFrame;


public class AudioCapture extends JFrame implements ActionListener
{
    boolean stopCapture = false;
    ByteArrayOutputStream byteArrayOutputStream;
    AudioFormat audioFormat;
    TargetDataLine targetDataLine;
    AudioInputStream audioInputStream;
    SourceDataLine sourceDataLine;
   
    final JButton startButton = new JButton("Start");
    final JButton stopButton = new JButton("Stop");
    final JButton playButton = new JButton("Playback");
    public static void main(String[] args)
    {
        AudioCapture audioCapture=new AudioCapture();
        audioCapture.setVisible(true);
        audioCapture.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public AudioCapture()
    {
        setSize(400,80);
        setLocation(100,100);
        this.setLayout(new GridLayout(1,3,20,20));
        this.setResizable(false);
       
        stopButton.setEnabled(false);
        playButton.setEnabled(false);
       
        add(startButton);
        add(stopButton);
        add(playButton);
       
       
        startButton.addActionListener(this);
        stopButton.addActionListener(this);
        playButton.addActionListener(this);
       
    }
   
    public Insets getInsets()
    {
        return new Insets(40,20,10,20);
    }
    @Override
    public void actionPerformed(ActionEvent ae)
    {
        if(ae.getSource()==startButton)
        {
            startButton.setEnabled(false);
            stopButton.setEnabled(true);
            playButton.setEnabled(false);
           
            audioFormat=new AudioFormat(8000.0F,16,1,true,false);
            DataLine.Info dataLineInfo=new DataLine.Info(TargetDataLine.class,audioFormat);
            try
            {
                targetDataLine=(TargetDataLine)AudioSystem.getLine(dataLineInfo);
                targetDataLine.open(audioFormat);
                targetDataLine.start();
               
                new CaptureThread(this);
               
            }
            catch (LineUnavailableException e)
            {
                e.printStackTrace();
            }
        }
        else if(ae.getSource()==stopButton)
        {
            startButton.setEnabled(true);
            stopButton.setEnabled(false);
            playButton.setEnabled(true);
           
            stopCapture=true;
        }
        else if(ae.getSource()==playButton)
        {
            byte audioData[]=byteArrayOutputStream.toByteArray();
            InputStream byteArrayInputStream=new ByteArrayInputStream(audioData);
            AudioFormat audioFormat=new AudioFormat(8000.0F,16,1,true,false);
            audioInputStream=new AudioInputStream(byteArrayInputStream,audioFormat,audioData.length/audioFormat.getFrameSize());
           
            DataLine.Info dataLineInfo =new DataLine.Info(SourceDataLine.class,audioFormat);
            try
            {
                sourceDataLine = (SourceDataLine)AudioSystem.getLine(dataLineInfo);
                sourceDataLine.open(audioFormat);
                sourceDataLine.start();
               
                new PlayThread(this);
               
            }
            catch (LineUnavailableException e)
            {
                e.printStackTrace();
            }
           
        }
    }
}
class CaptureThread implements Runnable
{
    byte tempBuffer[]=new byte[10000];
    AudioCapture audioCaptureObj;
    CaptureThread(AudioCapture audioCaptureObj)
    {
        this.audioCaptureObj=audioCaptureObj;
        Thread th=new Thread(this);
        th.start();
    }
    @Override
    public void run() {
        // TODO Auto-generated method stub

        audioCaptureObj.byteArrayOutputStream=new ByteArrayOutputStream();
        audioCaptureObj.stopCapture=false;
        while(!audioCaptureObj.stopCapture)
        {
            int count=audioCaptureObj.targetDataLine.read(tempBuffer,0,tempBuffer.length);
            if(count>0)
            {
                audioCaptureObj.byteArrayOutputStream.write(tempBuffer, 0, count);
            }
        }
        try {
            audioCaptureObj.byteArrayOutputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
class PlayThread implements Runnable
{
    byte tempBuffer[] = new byte[10000];
    AudioCapture audioCaptureObj;
    public PlayThread(AudioCapture audioCaptureObj)
    {
        this.audioCaptureObj=audioCaptureObj;
        Thread th=new Thread(this);
        th.start();
    }
    @Override
    public void run()
    {
        int count;
        try {
            while((count=audioCaptureObj.audioInputStream.read(tempBuffer,0,tempBuffer.length))!=-1)
            {
                if(count>0)
                {
                    audioCaptureObj.sourceDataLine.write(tempBuffer, 0, count);
                }
            }
            audioCaptureObj.sourceDataLine.drain();
            audioCaptureObj.sourceDataLine.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
/*********************************************************************************/

Friday, 23 May 2014

Illustration of onclick : HTML DOM Mouse Event

The following code shows how to create an alert dialog box and change the text on your main HTML page using a javaScript junction.

/****************************************************************************/


<html>
    <head>
        <title>My First Java Script</title>
    </head>
    <body>
        <button type="button" onClick="MyFunction()">Click me!</button>
        <p id="demo">Hello Lavish Kothari</p>
     
        <script>
            function MyFunction()
            {
                alert("the Text will now be converted");
                document.getElementById("demo").innerHTML="HELLO LAVISH KOTHARI";
            }
        </script>
    </body>
</html>

/****************************************************************************/

<html>
    <body>

        <h1>My First JavaScript</h1>

        <p id="demo">JavaScript can change the style of an HTML element.</p>

        <script>
            function myFunction() {
                var x = document.getElementById("demo");
                x.style.fontSize = "25px";          
                x.style.color = "red";
            }
        </script>

        <button type="button" onclick="myFunction()">Click Me!</button>

    </body>
</html>

/****************************************************************************/
    similarly you can use
   
    onclick : The event occurs when the user clicks on an element
    ondblclick : The event occurs when the user double-clicks on an element
    onmousedown : The event occurs when a user presses a mouse button over an element
    onmousemove : The event occurs when the pointer is moving while it is over an element
    onmouseover : The event occurs when the pointer is moved onto an element
    onmouseout : The event occurs when a user moves the mouse pointer out of an element
    onmouseup : The event occurs when a user releases a mouse button over an element