Friday 31 May 2013

Java program to simulate FIFO and LRU page replacement algorithms

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

import javax.swing.JFileChooser;

/**
 * This class reads a user chosen file for the reference string
 * (there should be spaces between the values in the string)
 * and simulates the selected page replacement policy i.e.
 * FIFO or LRU. It displays the status of page frames at each
 * new value in the string and saves the paging report in a plain
 * text file.
 * @author Dixit Bhatta
 * **/
public class pgReplace {

public static void main(String[] args) throws IOException {
ArrayList<Integer> ref = new ArrayList<Integer>();//creating new HashSet

try {
Scanner filein = new Scanner(getInputFileNameFromUser()); //open file
while(filein.hasNext()) {
String frame = filein.next();
int frm = Integer.parseInt(frame);
ref.add(frm);// add the integers to HashSet.
}//end of while

filein.close();//close the file

} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}

//display the size if it the set is not empty
if(!ref.isEmpty()){
int size = ref.size();
System.out.println("The length of the Reference String is: " + size);
}
//printing the read reference string using an iterator
Iterator<Integer> iter = ref.iterator();
while (iter.hasNext())
System.out.print(iter.next() +" ");

//converting the arraylist to an array
Integer frame[] = new Integer[ref.size()];
   frame = ref.toArray(frame);

   System.out.printf("\nSelect the Page Replacement Algorithm: ");
   System.out.printf("\n1.FIFO\n2.LRU\n? ");

   Scanner sc = new Scanner(System.in);
   while (!sc.hasNextInt()) {
       sc.next(); // discard next token, which isn't a valid int
   }
   int ch = sc.nextInt();

switch(ch){
   case 1: fifo(frame,ref.size());
    break;
   case 2: lru(frame,ref.size());
    break;
   default: System.out.printf("\nInvlaid Choice");
   }
 
}
/**Simulates LRU page replacement for given reference string
* @throws IOException **/
public static void lru(Integer[] page, int n) throws IOException {
int [] frame = new int[10];
int []used = new int[10];
int index = 0;
int i,j,k,temp;
int flag=0,pf=0;
BufferedWriter write = new BufferedWriter(new FileWriter("file.txt"));
PrintWriter out = new PrintWriter(write);
System.out.printf("\tLRU Page Replacement");
System.out.printf("\nEnter number of Frames: ");
Scanner sc = new Scanner(System.in);
   while (!sc.hasNextInt()) {
       sc.next(); // discard next token, which isn't a valid int
   }
   int nf = sc.nextInt();
for(i=0;i<nf;i++)
frame[i]= -1;

for(i=0;i<n;i++){
flag=0;
for(j=0;j<nf;j++){
if(frame[j]==page[i]){//no fault
System.out.printf("\n%d: ", page[i]);
out.printf("\n%d: ", page[i]);
flag=1;
break;
}
}
if(flag==0){//fault occurs
for(j=0;j<nf;j++)
used[j]=0;//all unused initially
//moving through pages and searching recently used pages
try{
for(j = 0,temp= i-1;j < nf-1;j++,temp--){
for(k = 0;k < nf;k++){
if(frame[k]==page[temp])
used[k]=1;
//mark the recently used pages
}
}
}
catch(ArrayIndexOutOfBoundsException e){
}
for(j=0;j<nf;j++)
if(used[j]==0)
index=j;
//replace the lru page with new page
frame[index]=page[i];
System.out.printf("\n%d: ", page[i]);
System.out.printf("--->F ");
out.printf("\n%d: ", page[i]);
out.printf("--->F ");
pf++;//no of page faults
}

for(k= nf-1;k>=0;k--)
if(frame[k] != -1){
System.out.printf(" %d",frame[k]);//print frames
out.printf(" %d",frame[k]);
}
}

System.out.printf("\nNumber of page faults is: %d ",pf);
out.printf("\nNumber of page faults is: %d ",pf);
out.close();
write.close();
}

/**Simulates FIFO page replacement for given reference string
* @throws IOException **/
public static void fifo(Integer[] pages, int pg) throws IOException {
int [] frame = new int[25];
int i,k,avail,count=0;
BufferedWriter write = new BufferedWriter(new FileWriter("file.txt"));
PrintWriter out = new PrintWriter(write);
System.out.printf("\tFIFO Page Replacement");
System.out.printf("\nEnter number of Frames: ");
Scanner sc = new Scanner(System.in);
   while (!sc.hasNextInt()) {
       sc.next(); // discard next token, which isn't a valid int
   }
   int nof = sc.nextInt();
for(i=0;i<nof;i++)
frame[i]= -1;

   int j=0;
   System.out.printf("\n");
   out.printf("\n");
for(i=0;i<pg;i++){
System.out.printf("%d\t",pages[i]);
out.printf("%d\t",pages[i]);
avail=0;
for(k=0;k<nof;k++)
if(frame[k]==pages[i])
avail=1;

  if (avail==0){
frame[j]=pages[i];
j=(j+1) % nof;
count++;

for(k=0;k<nof;k++)
if(frame[k]!=-1){
System.out.printf("%d",frame[k]);
out.printf("%d",frame[k]);
}
   
System.out.printf("-->F");
out.printf("-->F");
     }

     if(avail==1){
   for(k=0;k<nof;k++)
    if(frame[k]!=-1){
    System.out.printf("%d",frame[k]);
    out.printf("%d",frame[k]);
    }
     }
     System.out.printf("\n");
     out.printf("\n");
}
System.out.printf("\nNo of Faults: %d",count);
out.printf("\nNo of Faults: %d",count);
out.close();
write.close();
}
/**
* Lets the user select an input file using a standard file
* selection dialog box. If the user cancels the dialog
* without selecting a file, the return value is null.
*/
static File getInputFileNameFromUser() {
JFileChooser fileDialog = new JFileChooser();
fileDialog.setDialogTitle("Select File for Input");
int option = fileDialog.showOpenDialog(null);
if (option != JFileChooser.APPROVE_OPTION)
return null;
else
return fileDialog.getSelectedFile();
}//end of choosing file

}

©Dixit Bhatta 2013

Thursday 30 May 2013

Java program to reverse the content of a text file

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Scanner;

import javax.swing.JFileChooser;

/**
 * This class reads a user chosen file, reads its words
 * reverses the order in which the words are stored in
 * the file i.e. the last word becomes first and the first
 * word becomes last.
 * @author Dixit Bhatta
 * **/
public class revFile {

public static void main(String[] args) throws IOException{
ArrayList<String> rev = new ArrayList<String>();//creating new ArrayList
String absolutePath = null; //to store path of the file
try {
File file = getInputFileNameFromUser();
//store the path of file to modify it later
absolutePath = file.getAbsolutePath();
Scanner filein = new Scanner(file); //open file
while(filein.hasNext()) {
String frame = filein.next();
rev.add(frame);// add the strings i.e. words to the ArrayList.
}//end of while

filein.close();//close the file

} catch (FileNotFoundException e) {//handle exception in case of error
System.err.println("FileNotFoundException: " + e.getMessage());
}

//display the number of words if it the file is not empty
if(!rev.isEmpty()){
int size = rev.size();
System.out.println("The number of words in file is: " + size);
}
Collections.reverse(rev);//reverse the arraylist
//use buffered writer and print writer to write into the file
BufferedWriter write = new BufferedWriter(new FileWriter(absolutePath));
PrintWriter out = new PrintWriter(write);
//writing the strings in the file using an iterator
Iterator<String> iter = rev.iterator();
while (iter.hasNext())
out.write(iter.next() + " ");
out.close();
}

/**
* Lets the user select an input file using a standard file
* selection dialog box. If the user cancels the dialog
* without selecting a file, the return value is null.
*/
static File getInputFileNameFromUser() {
JFileChooser fileDialog = new JFileChooser();
fileDialog.setDialogTitle("Select File for Input");
int option = fileDialog.showOpenDialog(null);
if (option != JFileChooser.APPROVE_OPTION)
return null;
else
return fileDialog.getSelectedFile();
}//end of choosing file


}

©Dixit Bhatta 2013

Sunday 26 May 2013

C program for implementing Restoring Division algorithm

/*Program for implementing Restoring Division algorithm.*/
#include <stdio.h>
#include <conio.h>
#include <math.h>

int a=0,b=0,c=0,com[5]={1,0,0,0,0},s=0;
int anum[5]={0},anumcp[5] ={0},bnum[5]={0};
int acomp[5]={0},bcomp[5]={0},rem[5]={0},quo[5]={0},res[5]={0};

void binary(){
     a = fabs(a);
     b = fabs(b);
     int r, r2, i, temp;
     for(i = 0; i < 5; i++){
           r = a % 2;
           a = a / 2;
           r2 = b % 2;
           b = b / 2;
           anum[i] = r;
           anumcp[i] = r;
           bnum[i] = r2;
           if(r2 == 0){
                bcomp[i] = 1;
           }
           if(r == 0){
                acomp[i] =1;
           }
     }
   //part for two's complementing
   c = 0;
   for( i = 0; i < 5; i++){
           res[i] = com[i]+ bcomp[i] + c;
           if(res[i]>=2){
                c = 1;
           }
           else
                c = 0;
           res[i] = res[i]%2;
     }
   for(i = 4; i>= 0; i--){
     bcomp[i] = res[i];
   }
}
void add(int num[]){
     int i;
     c = 0;
     for( i = 0; i < 5; i++){
           res[i] = rem[i]+ num[i] + c;
           if(res[i]>=2){
                c = 1;
           }
           else
                c = 0;
           res[i] = res[i]%2;
     }
     for(i = 4; i>= 0; i--){
           rem[i] = res[i];
           printf("%d",rem[i]);
     }
     printf(":");
     for(i = 4; i>= 0; i--){
           printf("%d",anumcp[i]);
     }
}
void shl(){//for shift left
     int i;
     for(i = 4; i > 0  ; i--){//shift the remainder
           rem[i] = rem[i-1];
     }
     rem[0] = anumcp[4];
     for(i = 4; i > 0  ; i--){//shift the remtient
           anumcp[i] = anumcp[i-1];
     }
     anumcp[0] = 0;
     printf("\nSHIFT LEFT: ");//display together
     for(i = 4; i>= 0; i--){
           printf("%d",rem[i]);
     }
     printf(":");
     for(i = 4; i>= 0; i--){
           printf("%d",anumcp[i]);
     }
}

void main(){
     clrscr();
     int i;
     printf("\t\tRESTORING DIVISION ALGORITHM");
     printf("\nEnter two numbers to multiply: ");
     printf("\nBoth must be less than 16");
     //simulating for two numbers each below 16
     do{
           printf("\nEnter A: ");
           scanf("%d",&a);
           printf("Enter B: ");
           scanf("%d",&b);
     }while(a>=16 || b>=16);

     printf("\nExpected Quotient = %d", a/b);
     printf("\nExpected Remainder = %d", a%b);
     if(a*b <0){
           s = 1;
     }

     binary();
     printf("\n\nUnsigned Binary Equivalents are: ");
     printf("\nA = ");
     for(i = 4; i>= 0; i--){
           printf("%d",anum[i]);
     }
     printf("\nB = ");
     for(i = 4; i>= 0; i--){
           printf("%d",bnum[i]);
     }
     printf("\nB'+ 1 = ");
     for(i = 4; i>= 0; i--){
           printf("%d",bcomp[i]);
     }
     printf("\n\n-->");
     //division part
     shl();
     for(i=0;i<5;i++){
           printf("\n-->"); //start with subtraction
           printf("\nSUB B: ");
           add(bcomp);
           if(rem[4]==1){//simply add for restoring
                printf("\n-->RESTORE");
                printf("\nADD B: ");
                anumcp[0] = 0;
                add(bnum);
           }
           else{
                anumcp[0] = 1;
           }
           if(i<4)
                shl();

     }
     printf("\n----------------------------");
     printf("\nSign of the result = %d",s);
     printf("\nRemainder is = ");
     for(i = 4; i>= 0; i--){
           printf("%d",rem[i]);
     }
     printf("\nQuotient is = ");
     for(i = 4; i>= 0; i--){
           printf("%d",anumcp[i]);
     }
getch();

}

Saturday 25 May 2013

C++ Tutorial 1: Function Overloading

In general, overloading refers to using same things for different purposes. In case of functions, when the same function name is used for different tasks, it is called as function overloading. Say if we want to calculate area of certain shapes, it would be easier for us to call the function with the same name as "area()" for all the shapes than remembering individual names. So, function overloading is one of the important features in Object Oriented Programming. In C++, when an overloaded function is called, the function with matching arguments and return type is called and executed. See the example below for better understanding of this concept.

/*Write a program using function overloading that calculates the volume of a cube, a cylinder and a rectangular box. Use the overloaded functions with suitable arguments to achieve this.*/
#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
#define PI 3.14159

float volume(int side){     //for volume of a cube
return (side*side*side);
}
float volume(int radius, int height){     //for volume of a cylinder
return (PI*radius*radius*height);
}
float volume(int length, int width, int height){     //for volume of a rectangular box
return (length*width*height);
}

void main(){
clrscr();
   int side, r, ht, l, w, h, ch;
   float vol;
   cout<<"Select the shape to find volume: ";
   cout<<endl<<"1.Cube"<<endl<<"2.Cylinder"<<endl<<"3.Rectangular Box"<<endl<<":";
   cin>>ch;

    switch(ch){
      case 1:
          cout<<endl<<"Enter the length of a side: ";
          cin>>side;
          vol = volume(side);
          break;
case 2:
          cout<<endl<<"Enter the radius: ";
          cin>>r;
            cout<<endl<<"Enter the height: ";
            cin>>ht;
          vol = volume(r,ht);
            break;
         case 3:
          cout<<endl<<"Enter the length: ";
          cin>>l;
            cout<<endl<<"Enter the width: ";
            cin>>w;
            cout<<endl<<"Enter the height: ";
            cin>>h;
          vol = volume(l,w,h);
            break;
         default:
          cout<<endl<<"Invalid Choice!!";
            goto end;
      }
cout<<endl<<"Volume = "<<vol<<" cubic units";
end:
   getch();
}

©Dixit Bhatta 2013

Tuesday 14 May 2013

C program for Booth's multiplication algorithm


Pseudocode:

1.Start
2.Product = 0
3.Ask user to enter two decimal numbers: n1, n2
4.Convert them into binary and store in arrays num1 and num2
5.Two’s complement the numbers if they are negative
6.Two’s complement num2 and store as ncom
7.Create a copy of num1 as ncopy
8.Set q = 0
9.If num1[i] = = q, arithmetic shift product : ncopy
10.Else if num1[i] == 1 and q ==0, add ncom to product and arithmetic shift product : ncopy
11.Else add num2 to product and arithmetic shift product : ncopy
12.In each step set q = num1[i] after shift operation
13.Repeat steps 9,10,11 and 12 until all bits of num1 are shifted out
14.Display final result as product : ncopy
15.End

Program:
/*Program for implementing Booth's multiplication algorithm.*/
#include <stdio.h>
#include <conio.h>
#include <math.h>

int a=0,b=0,c=0,a1=0,b1=0,com[5]={1,0,0,0,0};
int anum[5]={0},anumcp[5] ={0},bnum[5]={0};
int acomp[5]={0},bcomp[5]={0},pro[5]={0},res[5]={0};

void binary(){
     a1 = fabs(a);
     b1 = fabs(b);
     int r, r2, i, temp;
     for(i = 0; i < 5; i++){
           r = a1 % 2;
           a1 = a1 / 2;
           r2 = b1 % 2;
           b1 = b1 / 2;
           anum[i] = r;
           anumcp[i] = r;
           bnum[i] = r2;
           if(r2 == 0){
                bcomp[i] = 1;
           }
           if(r == 0){
                acomp[i] =1;
           }
     }
   //part for two's complementing
   c = 0;
   for( i = 0; i < 5; i++){
           res[i] = com[i]+ bcomp[i] + c;
           if(res[i]>=2){
                c = 1;
           }
           else
                c = 0;
           res[i] = res[i]%2;
     }
   for(i = 4; i>= 0; i--){
     bcomp[i] = res[i];
   }
   //in case of negative inputs
   if(a<0){
      c = 0;
     for(i = 4; i>= 0; i--){
           res[i] =0;
     }
     for( i = 0; i < 5; i++){
           res[i] = com[i]+ acomp[i] + c;
           if(res[i]>=2){
                c = 1;
           }
           else
                c = 0;
           res[i] = res[i]%2;
     }
     for(i = 4; i>= 0; i--){
           anum[i] = res[i];
           anumcp[i] = res[i];
     }

   }
   if(b<0){
     for(i=0;i<5;i++){
           temp = bnum[i];
           bnum[i] = bcomp[i];
           bcomp[i] = temp;
     }
   }
}
void add(int num[]){
     int i;
   c = 0;
     for( i = 0; i < 5; i++){
           res[i] = pro[i]+ num[i] + c;
           if(res[i]>=2){
                c = 1;
           }
           else
                c = 0;
           res[i] = res[i]%2;
     }
     for(i = 4; i>= 0; i--){
     pro[i] = res[i];
           printf("%d",pro[i]);
     }
   printf(":");
   for(i = 4; i>= 0; i--){
           printf("%d",anumcp[i]);
     }
}
void arshift(){//for arithmetic shift right
     int temp = pro[4], temp2 = pro[0],i;
     for(i = 1; i <5  ; i++){//shift the MSB of product
           pro[i-1] = pro[i];
     }
     pro[4] = temp;
   for(i = 1; i < 5  ; i++){//shift the LSB of product
           anumcp[i-1] = anumcp[i];
     }
   anumcp[4] = temp2;
     printf("\nAR-SHIFT: ");//display together
   for(i = 4; i>= 0; i--){
           printf("%d",pro[i]);
     }
   printf(":");
   for(i = 4; i>= 0; i--){
           printf("%d",anumcp[i]);
     }
}

void main(){
     clrscr();
   int i, q=0;
     printf("\t\tBOOTH'S MULTIPLICATION ALGORITHM");
     printf("\nEnter two numbers to multiply: ");
     printf("\nBoth must be less than 16");
   //simulating for two numbers each below 16
     do{
           printf("\nEnter A: ");
           scanf("%d",&a);
           printf("Enter B: ");
           scanf("%d",&b);
     }while(a>=16 || b>=16);

     printf("\nExpected product = %d", a*b);
  

     binary();
     printf("\n\nBinary Equivalents are: ");
     printf("\nA = ");
     for(i = 4; i>= 0; i--){
           printf("%d",anum[i]);
     }
     printf("\nB = ");
     for(i = 4; i>= 0; i--){
           printf("%d",bnum[i]);
     }
   printf("\nB'+ 1 = ");
   for(i = 4; i>= 0; i--){
           printf("%d",bcomp[i]);
     }
     printf("\n\n");
     for(i=0;i<5;i++){
           if(anum[i] == q){//just shift for 00 or 11
           printf("\n-->");
                arshift();
         q = anum[i];
           }
           else if(anum[i] == 1 && q == 0){//subtract and shift for 10
           printf("\n-->");
         printf("\nSUB B: ");
                add(bcomp);//add two's complement to implement subtraction
                arshift();
         q = anum[i];
           }
           else{//add ans shift for 01
           printf("\n-->");
         printf("\nADD B: ");
                add(bnum);
                arshift();
         q = anum[i];
           }
     }
  
     printf("\nProduct is = ");
     for(i = 4; i>= 0; i--){
           printf("%d",pro[i]);
     }
   for(i = 4; i>= 0; i--){
           printf("%d",anumcp[i]);
     }
getch();
}

©Dixit Bhatta 2013