0% found this document useful (0 votes)
4 views61 pages

package A1 (1)

Uploaded by

chetanaingle7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views61 pages

package A1 (1)

Uploaded by

chetanaingle7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 61

package A1;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.Collections;

import java.util.HashMap;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;

import java.util.StringTokenizer;

import A1.LitTuple;

import A1.SymTuple;

import A1.Tuple;

class Tuple {

//m_class specifies class of the mnemonic such as IS, DL, or AD

String mnemonic, m_class, opcode;

int length;

Tuple() {}
Tuple(String s1, String s2, String s3, String s4) {

mnemonic = s1;

m_class = s2;

opcode = s3;

length = Integer.parseInt(s4);

class SymTuple {

String symbol, address;

int length;

SymTuple(String s1, String s2, int i1) {

symbol = s1;

address = s2;

length = i1;

class LitTuple {

String literal, address;

int length;

LitTuple() {}
LitTuple(String s1, String s2, int i1) {

literal = s1;

address = s2;

length = i1;

public class Assembler_PassOne_V2 {

static int lc,iSymTabPtr=0, iLitTabPtr=0, iPoolTabPtr=0;

static int poolTable[] = new int[10];

static Map<String,Tuple> MOT;

static Map<String,SymTuple> symtable;

static ArrayList<LitTuple> littable;

static Map<String, String> regAddressTable;

static PrintWriter out_pass2;

static PrintWriter out_pass1;

static int line_no;

public static void main(String[] args) throws Exception{

initializeTables();

System.out.println("Name: Chetana Ingle");

System.out.println("Roll no.50 ");

System.out.println("====== PASS 1 OUTPUT ======\n");

pass1();
}

static void pass1() throws Exception {

BufferedReader input = new BufferedReader(new InputStreamReader(new


FileInputStream("src/A1/input.txt")));

out_pass1 = new PrintWriter(new FileWriter("src/A1/output_pass1.txt"),


true);

PrintWriter out_symtable = new PrintWriter(new


FileWriter("src/A1/symtable.txt"), true);

PrintWriter out_littable = new PrintWriter(new


FileWriter("src/A1/littable.txt"), true);

String s;

//Read from input file one line at a time

lc=0;

while((s = input.readLine()) != null) {

StringTokenizer st = new StringTokenizer(s, " ", false);

//For each line, separate out the tokens

String s_arr[] = new String[st.countTokens()];

for(int i=0 ; i < s_arr.length ; i++) {

s_arr[i] = st.nextToken();

if(s_arr.length == 0){

continue;

int curIndex = 0;

//Contains a value in the label field

if(s_arr.length == 3){

String label = s_arr[0];

insertIntoSymTab(label,lc+"");
curIndex = 1;

String curToken = s_arr[curIndex];

//Get current tuple from opcode Table

Tuple curTuple = MOT.get(curToken);

String intermediateStr="";

//Analyze current token to check class of token (IS, DL, AD)

if(curTuple.m_class.equalsIgnoreCase("IS")){

intermediateStr += lc + " (" + curTuple.m_class + "," +


curTuple.opcode + ") ";

lc += curTuple.length;

intermediateStr += processOperands(s_arr[curIndex+1]);

else if(curTuple.m_class.equalsIgnoreCase("AD")){

if(curTuple.mnemonic.equalsIgnoreCase("START")){

intermediateStr += lc + " (" + curTuple.m_class + ","


+ curTuple.opcode + ") ";

lc = Integer.parseInt(s_arr[curIndex+1]);

intermediateStr += "(C," + (s_arr[curIndex+1]) + ") ";

else if(curTuple.mnemonic.equalsIgnoreCase("LTORG")){

intermediateStr +=processLTORG();

else if(curTuple.mnemonic.equalsIgnoreCase("END")){

intermediateStr += lc + " (" + curTuple.m_class + ","


+ curTuple.opcode + ") \n";

intermediateStr +=processLTORG();
//break;

else if(curTuple.m_class.equalsIgnoreCase("DL")){

intermediateStr += lc + " (" + curTuple.m_class + "," +


curTuple.opcode + ") ";

if(curTuple.mnemonic.equalsIgnoreCase("DS")){

lc += Integer.parseInt(s_arr[curIndex+1]);

else if(curTuple.mnemonic.equalsIgnoreCase("DC")){

lc += curTuple.length;

intermediateStr += "(C," + s_arr[curIndex+1] + ") ";

//Print the instruction in the intermediate file

System.out.println(intermediateStr);

out_pass1.println(intermediateStr);

//Add the length of the instruction in the location counter

//Close intermediate file

out_pass1.flush();

out_pass1.close();

//Print symbol table

System.out.println("====== Symbol Table ======");

SymTuple tuple;

Iterator<SymTuple> it = symtable.values().iterator();

String tableEntry;

while(it.hasNext()){
tuple = it.next();

tableEntry = tuple.symbol + "\t" + tuple.address ;

out_symtable.println(tableEntry);

System.out.println(tableEntry);

out_symtable.flush();

out_symtable.close();

//Print literal table

System.out.println("====== Literal Table ======");

LitTuple litTuple;

//Iterator<LitTuple> iterator = littable.values().iterator();

tableEntry = "";

for(int i=0; i<littable.size(); i++){

litTuple = littable.get(i);

tableEntry = litTuple.literal + "\t" + litTuple.address ;

out_littable.println(tableEntry);

System.out.println(tableEntry);

out_littable.flush();

out_littable.close();

static String processLTORG(){

//Process literal table and assign addresses to every literal in the table

LitTuple litTuple;

String intermediateStr = "";


for(int i=poolTable[iPoolTabPtr-1]; i<littable.size(); i++){

litTuple = littable.get(i);

litTuple.address = lc+"";

intermediateStr += lc + " (DL,02) (C," + litTuple.literal + ") \n";

lc++;

//Make a new entry in pool table;

poolTable[iPoolTabPtr] = iLitTabPtr;

iPoolTabPtr++;

return intermediateStr;

static String processOperands(String operands){

StringTokenizer st = new StringTokenizer(operands, ",", false);

//Separate out the tokens separated by comma

String s_arr[] = new String[st.countTokens()];

for(int i=0 ; i < s_arr.length ; i++) {

s_arr[i] = st.nextToken();

String intermediateStr = "", curToken;

for(int i=0; i <s_arr.length; i++){

curToken = s_arr[i];

if(curToken.startsWith("=")){

//Operand is a literal

//Extract literal from the string

StringTokenizer str = new StringTokenizer(curToken, "'",


false);

//Separate out the tokens separated by comma

String tokens[] = new String[str.countTokens()];


for(int j=0 ; j < tokens.length ; j++) {

tokens[j] = str.nextToken();

String literal = tokens[1];

insertIntoLitTab(literal,"");

intermediateStr += "(L," + (iLitTabPtr -1) + ")";

else if(regAddressTable.containsKey(curToken)){

//Operand is a register name

intermediateStr += "(RG," + regAddressTable.get(curToken)


+ ") ";

else{

//Operand is a symbol

insertIntoSymTab(curToken,"");

intermediateStr += "(S," + (iSymTabPtr -1) + ")";

return intermediateStr;

static void insertIntoSymTab(String symbol, String address){

//Check if the symbol is already present in the symbol table

if(symtable.containsKey(symbol)== true){

//Extract entry from symbol table

SymTuple s = symtable.get(symbol);

//Update its address field

s.address = address;
}

else{

//If symbol is not present in the symbol table, create a new entry

symtable.put(symbol, new SymTuple(symbol, address, 1));

iSymTabPtr++;

static void insertIntoLitTab(String literal, String address){

//If label is not present in the literal table, create a new entry

littable.add(iLitTabPtr, new LitTuple(literal, address, 1));

iLitTabPtr++;

static void initializeTables() throws Exception {

symtable = new LinkedHashMap<>();

littable = new ArrayList<>();

regAddressTable = new HashMap<>();

MOT = new HashMap<>();

String s,mnemonic;

BufferedReader br;

br = new BufferedReader(new InputStreamReader(new


FileInputStream("src/A1/mot.txt")));

while((s = br.readLine()) != null) {

StringTokenizer st = new StringTokenizer(s, " ", false);

mnemonic = st.nextToken();

MOT.put(mnemonic, (new Tuple(mnemonic, st.nextToken(),


st.nextToken(), st.nextToken())));
}

br.close();

//Initiallize register address table

regAddressTable.put("AREG", "1");

regAddressTable.put("BREG", "2");

regAddressTable.put("CREG", "3");

regAddressTable.put("DREG", "4");

//Initiallize pool table

poolTable[iPoolTabPtr] = iLitTabPtr;

iPoolTabPtr++;

Output:
package A2;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.LinkedHashMap;

import java.util.Map;

import java.util.StringTokenizer;

import A2.Tuple;

import A2.SymTuple;

import A2.LitTuple;

class Tuple {

//m_class specifies class of the mnemonic such as IS, DL, or AD

String mnemonic, m_class, opcode;

int length;

Tuple() {}

Tuple(String s1, String s2, String s3, String s4) {

mnemonic = s1;

m_class = s2;
opcode = s3;

length = Integer.parseInt(s4);

class SymTuple {

String symbol, address, length;

SymTuple(String s1, String s2, String i1) {

symbol = s1;

address = s2;

length = i1;

class LitTuple {

String literal, address, length;

LitTuple() {}

LitTuple(String s1, String s2, String i1) {

literal = s1;

address = s2;

length = i1;

}
public class Assembler_PassTwo {

static int lc,iSymTabPtr=0, iLitTabPtr=0, iPoolTabPtr=0;

static int poolTable[] = new int[10];

static Map<String,Tuple> MOT;

static ArrayList<SymTuple> symtable;

static ArrayList<LitTuple> littable;

static Map<String, String> regAddressTable;

static PrintWriter out_pass2;

static void initiallizeTables() throws Exception{

symtable = new ArrayList<>();

littable = new ArrayList<>();

regAddressTable = new HashMap<>();

//MOT = new HashMap<>();

String s;

BufferedReader br;

br = new BufferedReader(new InputStreamReader(new


FileInputStream("src/A2/symtable.txt")));

while((s = br.readLine()) != null) {

StringTokenizer st = new StringTokenizer(s, "\t", false);

symtable.add(new SymTuple(st.nextToken(), st.nextToken(), ""));

br.close();
br = new BufferedReader(new InputStreamReader(new
FileInputStream("src/A2/littable.txt")));

while((s = br.readLine()) != null) {

StringTokenizer st = new StringTokenizer(s, "\t", false);

littable.add(new LitTuple(st.nextToken(), st.nextToken(), ""));

br.close();

//Initiallize register address table

regAddressTable.put("AREG", "1");

regAddressTable.put("BREG", "2");

regAddressTable.put("CREG", "3");

regAddressTable.put("DREG", "4");

static void pass2() throws Exception{

BufferedReader input = new BufferedReader(new InputStreamReader(new


FileInputStream("src/A2/output_pass1.txt")));

out_pass2 = new PrintWriter(new FileWriter("src/A2/output_pass2.txt"),


true);

String s;

//Read from intermediate file one line at a time

while((s = input.readLine()) != null) {

//Replace all ( and ) characters by a blank string

s=s.replaceAll("(\\()", " ");

s=s.replaceAll("(\\))", " ");

//For each line, separate out the tokens

String ic_tokens[] = tokenizeString(s, " ");


if(ic_tokens == null || ic_tokens.length==0){

continue;

String output_str = "";

//Second token contains mnemonic class and opcode

String mnemonic_class = ic_tokens[1];

//Separate the mnemonic and its opcode which are separated by a


comma

String m_tokens[] = tokenizeString(mnemonic_class, ",");

//Write the second token as is in the output file

if(m_tokens[0].equalsIgnoreCase("IS")){

//First token is location counter which will be output as it is

output_str += ic_tokens[0] + " ";

//Output the opcode of the instruction

output_str += m_tokens[1] + " ";

String opr_tokens[];

for(int i = 2; i <ic_tokens.length; i++){

opr_tokens = tokenizeString(ic_tokens[i], ",");

if(opr_tokens[0].equalsIgnoreCase("RG")){

output_str += opr_tokens[1] + " ";

else if(opr_tokens[0].equalsIgnoreCase("S")){

int index = Integer.parseInt(opr_tokens[1]);

output_str += symtable.get(index).address +
" ";
}

else if(opr_tokens[0].equalsIgnoreCase("L")){

int index = Integer.parseInt(opr_tokens[1]);

output_str += littable.get(index).address + "


";

else if(m_tokens[0].equalsIgnoreCase("DL")){

//First token is location counter which will be output as it is

output_str += ic_tokens[0] + " ";

if(m_tokens[1].equalsIgnoreCase("02")){

//Process for operands of mnemonic DC

String opr_tokens[] = tokenizeString(ic_tokens[2],


",");

output_str += "00 00 " + opr_tokens[1] + " ";

System.out.println(output_str);

out_pass2.println(output_str);

static String[] tokenizeString(String str, String separator){

StringTokenizer st = new StringTokenizer(str, separator, false);

//Construct an array of the separated tokens

String s_arr[] = new String[st.countTokens()];


for(int i=0 ; i < s_arr.length ; i++) {

s_arr[i] = st.nextToken();

return s_arr;

public static void main(String[] args) throws Exception {

initiallizeTables();

System.out.println("Name: Chetana Ingle");

System.out.println("Roll no.50 ");

pass2();

Output:
package A3;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import java.util.StringTokenizer;

public class MacroProcessor_PassOne {

static List<String> MDT;

static Map<String, String> MNT;

static int mntPtr, mdtPtr;

static Map<String,String> ALA;

public static void main(String[] args) {

try{

pass1();

System.out.println("Name: Chetana Ingle");

System.out.println("Roll no.50 ");


}catch(Exception ex){

ex.printStackTrace();

static void pass1() throws Exception {

//Initiallize data structures

MDT = new ArrayList<String>();

MNT = new LinkedHashMap<String, String>();

ALA = new HashMap<String,String>();

mntPtr =0; mdtPtr = 0;

BufferedReader input = new BufferedReader(new InputStreamReader(new


FileInputStream("src/A3/input.txt")));

PrintWriter out_pass1 = new PrintWriter(new


FileWriter("src/A3/output_pass1.txt"), true);

PrintWriter out_mnt = new PrintWriter(new FileWriter("src/A3/MNT.txt"),


true);

PrintWriter out_mdt = new PrintWriter(new FileWriter("src/A3/MDT.txt"),


true);

String s;

boolean processingMacroDefinition = false;

boolean processMacroName = false;

System.out.println("============= Pass 1 Output ==============");

//Read from input file one line at a time

while((s = input.readLine()) != null) {


//For each line, separate out the tokens

String s_arr[] = tokenizeString(s," ");

//Analyze first token to check if it is a macro definition

String curToken = s_arr[0];

if(curToken.equalsIgnoreCase("MACRO")){

processingMacroDefinition = true;

processMacroName = true;

else if(processingMacroDefinition == true){

if(curToken.equalsIgnoreCase("MEND")){

MDT.add(mdtPtr++, s);

processingMacroDefinition = false;

continue;

//Insert Macro Name into MNT

if(processMacroName == true){

MNT.put(curToken, mdtPtr+"");

mntPtr++;

processMacroName = false;

processArgumentList(s_arr[1]);

MDT.add(mdtPtr,s);

mdtPtr++;

continue;

//Convert arguments in the definition into corresponding


indexed notation

//ADD &REG,&X == ADD #2,#1


String indexedArgList = processArguments(s_arr[1]);

MDT.add(mdtPtr++, curToken + " " + indexedArgList);

else{

//If line is not part of a Macro definition print the line as it is


in the output file

System.out.println(s);

out_pass1.println(s);

input.close();

//Print MNT

System.out.println("============= MNT ==============");

Iterator<String> itMNT = MNT.keySet().iterator();

String key, mntRow, mdtRow;

while(itMNT.hasNext()){

key = (String)itMNT.next();

mntRow = key + " " + MNT.get(key);

System.out.println(mntRow);

out_mnt.println(mntRow);

//Print MDT

System.out.println("============= MDT ==============");

for(int i = 0; i < MDT.size(); i++){

mdtRow = i + " " + MDT.get(i);

System.out.println(mdtRow);

out_mdt.println(mdtRow);
}

out_pass1.close();

out_mnt.close();

out_mdt.close();

static void processArgumentList(String argList){

StringTokenizer st = new StringTokenizer(argList, ",", false);

//For each macro definition, remove contents of the HashMap

//which are arguments from previous macro definition

ALA.clear();

int argCount = st.countTokens();

//Put all arguments for current macro definition in the HashMap

//with argument as key and argument index as value

String curArg;

for(int i=1 ; i <= argCount ; i++) {

curArg = st.nextToken();

if(curArg.contains("=")){

curArg = curArg.substring(0,curArg.indexOf("="));

ALA.put(curArg, "#"+i);

static String processArguments(String argList){

StringTokenizer st = new StringTokenizer(argList, ",", false);

int argCount = st.countTokens();


String curArg, argIndexed;

for(int i=0 ; i < argCount ; i++) {

curArg = st.nextToken();

argIndexed = ALA.get(curArg);

argList = argList.replaceAll(curArg, argIndexed);

return argList;

static String[] tokenizeString(String str, String separator){

StringTokenizer st = new StringTokenizer(str, separator, false);

//Construct an array of the separated tokens

String s_arr[] = new String[st.countTokens()];

for(int i=0 ; i < s_arr.length ; i++) {

s_arr[i] = st.nextToken();

return s_arr;

}
Output:
package A4;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.FileWriter;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.util.ArrayList;

import java.util.LinkedHashMap;

import java.util.List;

import java.util.Map;

import java.util.StringTokenizer;

public class MacroProcessor_PassTwo {

static List<String> MDT;

static Map<String, String> MNT;

static int mntPtr, mdtPtr;

static List<String> formalParams, actualParams;

public static void main(String[] args) {

try{

initiallizeTables();

System.out.println("Name: Chetana Ingle");

System.out.println("Roll no.50 ");

pass2();

}catch(Exception ex){
ex.printStackTrace();

static void pass2() throws Exception {

BufferedReader input = new BufferedReader(new InputStreamReader(new


FileInputStream("src/A4/output_pass1.txt")));

PrintWriter out_pass2 = new PrintWriter(new


FileWriter("src/A4/output_pass2.txt"), true);

System.out.println("============= Pass 2 Output ==============");

//Read from input file one line at a time

String s;

while((s = input.readLine()) != null) {

String s_arr[] = tokenizeString(s, " ");

//First token will either be a mnemonic or a macro call

if(MNT.containsKey(s_arr[0])){

//It is a macro call

//Create an array list of formal parameters

String actual_params[] = tokenizeString(s_arr[1], ",");

String param;

actualParams.clear();

for(int i =0; i <actual_params.length; i++){

param = actual_params[i];

if(param.contains("=")){

//If parameter specified a default value, the


value will go in the list instead of param name

param =
param.substring(param.indexOf("=")+1, param.length());
}

actualParams.add(param);

//Expand the macro call

mdtPtr = Integer.parseInt(MNT.get(s_arr[0]));

//Read macro definitaion starting from mdtPtr till MEND

String macroDef;

boolean createParamArray = true;

String def_tokens[] = {}, paramStr = "", printStr;

while(true){

//First line of macro definition is name and arglist

macroDef = MDT.get(mdtPtr);

if(createParamArray == true){

createFormalParamList(macroDef);

createParamArray = false;

else{

//Tokenize line of macro definition

def_tokens = tokenizeString(macroDef, " ");

//If the line is MEND, exit loop

if(def_tokens[0].equalsIgnoreCase("MEND")){

break;

else{

//Replace formal parameters with


actual parameters

paramStr =
replaceFormalParams(def_tokens[1]);
}

printStr = "+" + def_tokens[0] + " " +


paramStr;

System.out.println(printStr);

out_pass2.println(printStr);

mdtPtr++;

else{

//It is a line of normal assembly code

//Print the line as it is in the output file

System.out.println(s);

out_pass2.println(s);

input.close();

out_pass2.close();

static String replaceFormalParams(String formalParamList){

String returnStr = "";

//Replace # by blank string

formalParamList = formalParamList.replace("#", "");

//Separate formal params

String param_array[] = tokenizeString(formalParamList, ",");

int index;

String actualParam;
//For every parameter in the formal parameter list

for(int i = 0; i < param_array.length; i++){

index = Integer.parseInt(param_array[i]);

if(index <= actualParams.size()){

actualParam = actualParams.get(index-1);

else{

actualParam = formalParams.get(index-1);

returnStr += actualParam + ",";

//Strip last comma

returnStr = returnStr.substring(0,returnStr.length() -1);

return returnStr;

static void createFormalParamList(String macroDef){

//By processing macro call generate array of actual parameters

String argList, arg_array[];

String s_arr[] = tokenizeString(macroDef, " ");

//First array element will be macro name and second will be argument list

argList = s_arr[1];

//Separate the arguments in the list

arg_array = tokenizeString(argList, ",");

String param;

formalParams.clear();
for(int i=0; i <arg_array.length; i++){

param = arg_array[i];

if(param.contains("=")){

//If parameter specified a default value, the value will go in


the list instead of param name

param = param.substring(param.indexOf("=")+1,
param.length());

formalParams.add(param);

static void initiallizeTables() throws Exception{

MDT = new ArrayList<String>();

MNT = new LinkedHashMap<String, String>();

formalParams = new ArrayList<String>();

actualParams = new ArrayList<String>();

//Read contents of MNT.txt and create internal data structure

BufferedReader br;

String s;

br = new BufferedReader(new InputStreamReader(new


FileInputStream("src/A4/MNT.txt")));

while((s = br.readLine()) != null) {

StringTokenizer st = new StringTokenizer(s, " ", false);

MNT.put(st.nextToken(), st.nextToken());

br.close();
//Read contents of MDT.txt and create internal data structure

br = new BufferedReader(new InputStreamReader(new


FileInputStream("src/A4/MDT.txt")));

while((s = br.readLine()) != null) {

//For each line, separate out the tokens

String s_arr[] = tokenizeString(s," ");

if(s_arr.length == 0){

continue;

int index = Integer.parseInt(s_arr[0]);

if(s_arr.length == 2){

MDT.add(index, s_arr[1]);

else if(s_arr.length == 3){

MDT.add(index, s_arr[1] + " " + s_arr[2]);

br.close();

static String[] tokenizeString(String str, String separator){

StringTokenizer st = new StringTokenizer(str, separator, false);

//Construct an array of the separated tokens

String s_arr[] = new String[st.countTokens()];

for(int i=0 ; i < s_arr.length ; i++) {

s_arr[i] = st.nextToken();
}

return s_arr;

Output:
package C1;

import java.io.Closeable;

import java.util.Scanner;

class Process{

int pid;

int waitingTime;

int arrivalTime;

int burstTime;

int turnAroundTime;

int timeToComplete;

int completionTime = 0;

int priority;

Process(int pid, int sub,int bur){

this.pid = pid;

this.arrivalTime = sub;

this.burstTime = bur;

this.timeToComplete = burstTime;

Process(int pid, int sub,int bur, int priority){

this.pid = pid;

this.arrivalTime = sub;

this.burstTime = bur;

this.priority = priority;

this.timeToComplete = burstTime;
}

public class Scheduler{

static Scanner s = new Scanner(System.in);

public static void main(String[] args){

System.out.println("Name: Chetana Ingle");

System.out.println("Roll no.50 ");

System.out.println("Enter the number of processes:");

int n = s.nextInt();

Process[] myProcess = new Process[n];

for(int i=0;i<n;i++){

System.out.println("Enter Arrival time, Burst Time, and Priority: ");

int sub = s.nextInt();

int bur = s.nextInt();

int priority = s.nextInt();

myProcess[i] = new Process(i+1,sub,bur,priority);

System.out.println("Select the type of scheduler to be used:");

System.out.println("1. FCFS");

System.out.println("2. SJF (Preemptive)");

System.out.println("3. Priority (Non-preemptive");

System.out.println("4. Round Robin");

System.out.println("5. Exit");

System.out.println("Enter your choice:");

int choice = s.nextInt();


switch(choice){

case 1:

FCFS(myProcess);

break;

case 2:

SJF(myProcess);

break;

case 3:

PriorityScheduling(myProcess);

break;

case 4:

RoundRobin(myProcess);

break;

case 5:

s.close();

System.exit(1);

break;

default:

System.out.println("Incorrect Choice");

break;

s.close();

static void FCFS(Process myProcess[]){

int x=0;
//Arrange processes according to their arrival time in the ascending order

Process temp;

for(int i = 0; i < myProcess.length; i++){

for(int j = i; j < myProcess.length; j++){

if(myProcess[i].arrivalTime > myProcess[j].arrivalTime){

temp = myProcess[j];

myProcess[j] = myProcess[i];

myProcess[i] = temp;

for(int i=0;i<myProcess.length;i++){

x = x+myProcess[i].burstTime;

myProcess[i].completionTime = x;

myProcess[i].turnAroundTime = myProcess[i].completionTime -
myProcess[i].arrivalTime;

myProcess[i].waitingTime = myProcess[i].turnAroundTime -
myProcess[i].burstTime;

System.out.println("Process "+ myProcess[i].pid +":");

System.out.println("turnAroundTime\tCompletion\twaitingTimeing");

System.out.println(myProcess[i].turnAroundTime+"\t\t\t"+myProcess[i].comple
tionTime+"\t\t"+myProcess[i].waitingTime);

static void SJF(Process myProcess[]){


int curTimeInterval = 0, completedProcesses = 0;

Process curProcess;

//Traverse until all process gets completely executed.

curProcess = myProcess[0];

while(completedProcesses < myProcess.length){

for(int i=0; i < myProcess.length; i++){

if(myProcess[i].timeToComplete > 0){

curProcess = myProcess[i];

break;

System.out.println("Current Time Interval = " + curTimeInterval);

System.out.println("No of Processes Completed = " + completedProcesses);

//Find process with minimum remaining time at every single time lap

for(int i=0; i < myProcess.length; i++){

if(myProcess[i].arrivalTime > curTimeInterval ||


myProcess[i].timeToComplete == 0 ){

continue;

if(myProcess[i].timeToComplete < curProcess.timeToComplete){

curProcess = myProcess[i];

//Reduce its time by 1

curProcess.timeToComplete -= 1;

//Check if its remaining time becomes 0


if(curProcess.timeToComplete == 0){

//Increment the counter of process completion.

completedProcesses++;

//Completion time of current process = current_time +1;

curProcess.completionTime = curTimeInterval +1;

curTimeInterval++;

for(int i=0;i<myProcess.length;i++){

//Calculate waitingTimeing time for each process

//waitingTimeing Time = Completion time - arrival_time - burst_time

myProcess[i].waitingTime = myProcess[i].completionTime -
myProcess[i].arrivalTime - myProcess[i].burstTime;

//Find turnAroundTime time (waitingTimeing_time+burst_time)

myProcess[i].turnAroundTime = myProcess[i].waitingTime +
myProcess[i].burstTime;

System.out.println("Process "+ myProcess[i].pid +":");

System.out.println("turnAroundTime\tCompletion\twaitingTimeing");

System.out.println(myProcess[i].turnAroundTime+"\t\t\t"+myProcess[i].comple
tionTime+"\t\t"+myProcess[i].waitingTime);

static void PriorityScheduling(Process myProcess[]){


//Arrange processes according to their priority in the descending order

Process temp;

for(int i = 0; i < myProcess.length; i++){

for(int j = i; j < myProcess.length; j++){

if(myProcess[i].priority > myProcess[j].priority){

temp = myProcess[j];

myProcess[j] = myProcess[i];

myProcess[i] = temp;

int x = 0;

for(int i=0;i<myProcess.length;i++){

x = x+myProcess[i].burstTime;

myProcess[i].completionTime = x;

myProcess[i].turnAroundTime = myProcess[i].completionTime -
myProcess[i].arrivalTime;

myProcess[i].waitingTime = myProcess[i].turnAroundTime -
myProcess[i].burstTime;

System.out.println("Process "+ myProcess[i].pid +":");

System.out.println("turnAroundTime\tCompletion\twaitingTimeing");

System.out.println(myProcess[i].turnAroundTime+"\t\t\t"+myProcess[i].comple
tionTime+"\t\t"+myProcess[i].waitingTime);

}
static void RoundRobin(Process myProcess[]){

int curTimeInterval = 0, completedProcesses = 0;

System.out.println("Specify time quantum: ");

int quantum = s.nextInt();

// int quantum = 4;

//Keep traversing the all processes while all processes

//are not done. Do following for i'th process if it is

//not done yet.

while(completedProcesses < myProcess.length){

for(int i = 0; i < myProcess.length; i++){

if(myProcess[i].timeToComplete > 0 &&


myProcess[i].timeToComplete > quantum){

//Execute the process for the time quantum

curTimeInterval += quantum;

myProcess[i].timeToComplete -= quantum;

else{

if(myProcess[i].timeToComplete > 0){

//Execute last cycle for the process

curTimeInterval +=
myProcess[i].timeToComplete;

myProcess[i].timeToComplete = 0;

myProcess[i].completionTime =
curTimeInterval;
myProcess[i].turnAroundTime =
myProcess[i].completionTime - myProcess[i].arrivalTime;

myProcess[i].waitingTime =
myProcess[i].turnAroundTime - myProcess[i].burstTime;

completedProcesses++;

for(int i=0; i < myProcess.length; i++){

System.out.println("Process "+ myProcess[i].pid +":");

System.out.println("turnAroundTime\tCompletion\twaitingTimeing");

System.out.println(myProcess[i].turnAroundTime+"\t\t\t"+myProcess[i].comple
tionTime+"\t\t"+myProcess[i].waitingTime);

}
Output:
package A6;

import java.util.*;

public class Memory {

static void firstFit(int blockSize[], int m, int processSize[], int n) {

// Stores block id of the

// block allocated to a process

int allocation[] = new int[n];

// Initially no block is assigned to any process

for (int i = 0; i < allocation.length; i++)

allocation[i] = -1;

// pick each process and find suitable blocks

// according to its size ad assign to it

for (int i = 0; i < n; i++) {

for (int j = 0; j < m; j++) {

if (blockSize[j] >= processSize[i]) {

// allocate block j to p[i] process

allocation[i] = j;

// Reduce available memory in this block.

blockSize[j] -= processSize[i];

break;

}
}

System.out.println("\nProcess No.\tProcess Size\tBlock no.");

for (int i = 0; i < n; i++) {

System.out.print(" " + (i + 1) + "\t\t" + processSize[i] + "\t\t");

if (allocation[i] != -1)

System.out.print(allocation[i] + 1);

else

System.out.print("Not Allocated");

System.out.println();

static void worstFit(int blockSize[], int m, int processSize[], int n) {

// Stores block id of the block allocated to a

// process

int allocation[] = new int[n];

// Initially no block is assigned to any process

for (int i = 0; i < allocation.length; i++)

allocation[i] = -1;

// pick each process and find suitable blocks

// according to its size ad assign to it

for (int i = 0; i < n; i++) {

// Find the best fit block for current process


int wstIdx = -1;

for (int j = 0; j < m; j++) {

if (blockSize[j] >= processSize[i]) {

if (wstIdx == -1)

wstIdx = j;

else if (blockSize[wstIdx] < blockSize[j])

wstIdx = j;

// If we could find a block for current process

if (wstIdx != -1) {

// allocate block j to p[i] process

allocation[i] = wstIdx;

// Reduce available memory in this block.

blockSize[wstIdx] -= processSize[i];

System.out.println("\nProcess No.\tProcess Size\tBlock no.");

for (int i = 0; i < n; i++) {

System.out.print(" " + (i + 1) + "\t\t" + processSize[i] + "\t\t");

if (allocation[i] != -1)

System.out.print(allocation[i] + 1);

else

System.out.print("Not Allocated");
System.out.println();

static void NextFit(int blockSize[], int m, int processSize[], int n) {

// Stores block id of the block allocated to a

// process

int allocation[] = new int[n], j = 0, t = m - 1;

// Initially no block is assigned to any process

Arrays.fill(allocation, -1);

// pick each process and find suitable blocks

// according to its size ad assign to it

// pick each process and find sui table blocks

// according to its size ad assign to it

for (int i = 0; i < n; i++) {

// Do not start from beginning

while (j < m) {

if (blockSize[j] >= processSize[i]) {

// allocate block j to p[i] process

allocation[i] = j;

// Reduce available memory in this block.

blockSize[j] -= processSize[i];
// sets a new end point

t = (j - 1) % m;

break;

if (t == j) {

// sets a new end point

t = (j - 1) % m;

// breaks the loop after going through all memory


block

break;

// mod m will help in traversing the

// blocks from starting block after

// we reach the end.

j = (j + 1) % m;

System.out.print("\nProcess No.\tProcess Size\tBlock no.\n");

for (int i = 0; i < n; i++) {

System.out.print(i + 1 + "\t\t" + processSize[i] + "\t\t");

if (allocation[i] != -1) {

System.out.print(allocation[i] + 1);

} else {

System.out.print("Not Allocated");

}
System.out.println("");

static void bestFit(int blockSize[], int m, int processSize[], int n) {

// Stores block id of the block allocated to a

// process

int allocation[] = new int[n];

// Initially no block is assigned to any process

for (int i = 0; i < allocation.length; i++)

allocation[i] = -1;

// pick each process and find suitable blocks

// according to its size ad assign to it

for (int i = 0; i < n; i++) {

// Find the best fit block for current process

int bestIdx = -1;

for (int j = 0; j < m; j++) {

if (blockSize[j] >= processSize[i]) {

if (bestIdx == -1)

bestIdx = j;

else if (blockSize[bestIdx] > blockSize[j])

bestIdx = j;

}
// If we could find a block for current process

if (bestIdx != -1) {

// allocate block j to p[i] process

allocation[i] = bestIdx;

// Reduce available memory in this block.

blockSize[bestIdx] -= processSize[i];

System.out.println("\nProcess No.\tProcess Size\tBlock no.");

for (int i = 0; i < n; i++) {

System.out.print(" " + (i + 1) + "\t\t" + processSize[i] + "\t\t");

if (allocation[i] != -1)

System.out.print(allocation[i] + 1);

else

System.out.print("Not Allocated");

System.out.println();

static Scanner s = new Scanner(System.in);

public static void main(String[] args) {

System.out.println("Name:Chetana Ingle Roll no:- 50");

while(true) {

System.out.println("Enter the number of processes:");


int n = s.nextInt();

int processSize[] = new int[n];

for(int i=0;i<n;i++){

System.out.println("Enter the process: ");

int priority = s.nextInt();

processSize[i] = priority;

System.out.println("Enter the number of blocks:");

int m = s.nextInt();

int blockSize[] = new int[m];

for(int i=0;i<m;i++){

System.out.println("Enter the block: ");

int priority = s.nextInt();

blockSize[i] = priority;

System.out.println("Select the type of memory management to be used:");

System.out.println("1. First Fit");

System.out.println("2. Best Fit");

System.out.println("3. Worst Fit");

System.out.println("4. Next Fit");

System.out.println("5. Exit");

System.out.println("Enter your choice:");

int choice = s.nextInt();


switch(choice){

case 1:

firstFit(blockSize, m, processSize, n);

break;

case 2:

bestFit(blockSize, m, processSize, n);

break;

case 3:

worstFit(blockSize, m, processSize, n);

break;

case 4:

NextFit(blockSize, m, processSize, n);

break;

case 5:

s.close();

System.out.println("successfully exit");

System.exit(1);

break;

default:

System.out.println("Incorrect Choice");

break;

// s.close();

}
Output:
package D;

//Java implementation of above algorithm

import java.util.HashMap;

import java.util.HashSet;

import java.util.Iterator;

import java.util.ArrayList;

public class PageReplacement

static int pageFrames=0;

//Least Recently Used(LRU) Page Replacement Algorithm

static int lru(int referenceString[])

//This array list will contain all the pages that are currently in memory

ArrayList<Integer> pages = new ArrayList<Integer>(pageFrames);

// This hashmap will store least recently used indexes of the pages

HashMap<Integer, Integer> indexes = new HashMap<>();

// Start from initial page

int page_faults = 0, n = referenceString.length, curPage;

for (int i=0; i<n; i++)

curPage = referenceString[i];

// Check if the set can hold more pages


if (pages.size() < pageFrames)

// Insert it into set if not already present

// This represents a page fault

if (!pages.contains(curPage))

pages.add(curPage);

// increment page fault count

page_faults++;

displayPageFrames(pages, page_faults);

// Store the recently used index of each page

indexes.put(curPage, i);

// If the set is full then need to select a page to be replaced

// The page that is selected for replacement is the least recently used page

else

// Check if current page is not already present in the set

if (!pages.contains(curPage))

// The page having the lowest value of associated index will be the
least recently used page

int lru = Integer.MAX_VALUE, pageToBeReplaced =0;

int temp;
for(int j = 0; j < pages.size(); j++){

temp = pages.get(j);

if (indexes.get(temp) < lru)

lru = indexes.get(temp);

pageToBeReplaced = j;

indexes.remove(pages.get(pageToBeReplaced));

pages.set(pageToBeReplaced, curPage);

// Increment page fault count

page_faults++;

displayPageFrames(pages, page_faults);

// Update the current page index

indexes.put(curPage, i);

return page_faults;

//Optimal Page Replacement Algorithm

static int optimal(int referenceString[])

//This array list will contain all the pages that are currently in memory
ArrayList<Integer> pages = new ArrayList<Integer>(pageFrames);

// This hashmap will store least recently used indexes of the pages

HashMap<Integer, Integer> indexes = new HashMap<>();

// Start from initial page

int page_faults = 0, curPage, n = referenceString.length;

for (int i=0; i<n; i++)

curPage = referenceString[i];

// Check if the set can hold more pages

if (pages.size() < pageFrames)

// Insert it into set if not already present

// This represents a page fault

if (!pages.contains(curPage))

pages.add(curPage);

// increment page fault count

page_faults++;

displayPageFrames(pages, page_faults);

// Store the future index of the page

indexes.put(curPage, findNextIndex(curPage,i, referenceString));

}
// If the set is full then need to select a page to be replaced

// The page that is selected for replacement is the one that will not be
used for the longest period of time

else

// Check if current page is not already present in the set

if (!pages.contains(curPage))

// Find a page that is referenced farthest in the future

//This is implemented by finding a page that has greatest index


value

int optimal = Integer.MIN_VALUE, pageToBeReplaced =0;;

int temp;

for(int j = 0; j < pages.size(); j++){

temp = pages.get(j);

if (indexes.get(temp) > optimal)

optimal = indexes.get(temp);

pageToBeReplaced = j;

indexes.remove(pages.get(pageToBeReplaced));

pages.set(pageToBeReplaced, curPage);

// Increment page faults

page_faults++;
displayPageFrames(pages, page_faults);

// Update the current page index

indexes.put(curPage, findNextIndex(curPage,i, referenceString));

return page_faults;

static int findNextIndex(int curPage, int curIndex, int pages[]){

//Starting at the current index find the index of future use of the page

int i;

for(i= curIndex+1; i < pages.length; i++){

if(pages[i] == curPage){

break;

return i;

static void displayPageFrames(ArrayList<Integer> pages, int page_faults){

System.out.print("At PageFault- " + page_faults + " :: Pages- ");

for(int i = 0; i < pages.size(); i++) {

System.out.print(" " + pages.get(i));

System.out.print("\n");
}

// Driver method

public static void main(String args[])

{System.out.println("Name: Chetana Ingle");

System.out.println("Roll no.50 ");

int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2,1,2,0,1,7,0,1};

pageFrames = 3;

int pageFaults;

System.out.println("--- Implementing Least Recently Used Page Replacement


Algorithm -----");

pageFaults = lru(pages);

System.out.println("Number of page faults = " + pageFaults);

System.out.print("\n");

System.out.println("--- Implementing Optimal Page Replacement Algorithm --


---");

pageFaults = optimal(pages);

System.out.println("Number of page faults = " + pageFaults);

}
Output:

You might also like