Pruned old commits from testing branch. Created a new one for archiving untested codes.
This commit is contained in:
Executable
+65
@@ -0,0 +1,65 @@
|
||||
'''
|
||||
Every process is an obj with it's own wt,bt,at etc.
|
||||
the table is an obj of table class.
|
||||
Our table is just a list of process objects
|
||||
wt,tat,ct are calculated by waitCalculator()
|
||||
createTable() displays table neatly
|
||||
'''
|
||||
|
||||
|
||||
|
||||
|
||||
class ProcessClass:
|
||||
def __init__(self): #constructor in Py
|
||||
self.name =input("Enter Process Name: ")
|
||||
self.at = int(input("Enter Arrival Time: "))
|
||||
self.bt = int(input("Enter Burst Time: "))
|
||||
self.wt = 0
|
||||
self.tat = 0
|
||||
self.ct = 0
|
||||
def display(self):
|
||||
print(f"{self.name}:\t{self.at}\t{self.bt}\t{self.wt}\t{self.ct}\t\t{self.tat}\n")
|
||||
|
||||
class Table_class:
|
||||
|
||||
def __init__(self):
|
||||
self.table = []
|
||||
self.table1 = []
|
||||
print("Enter Processes:\n")
|
||||
while True:
|
||||
ch = int(input("\n\nAdd a new process?\t"))
|
||||
if ch:
|
||||
p = ProcessClass()
|
||||
self.table.append(p)
|
||||
else: break
|
||||
def fcfs(self):
|
||||
time = 0
|
||||
self.table1 = sorted(self.table, key= lambda p: p.at) #sorts array based on arrival time
|
||||
for cp in self.table1:
|
||||
cp.ct = cp.bt + time
|
||||
cp.wt = time - cp.at
|
||||
cp.tat = cp.wt + cp.bt
|
||||
time+= cp.bt
|
||||
def createTable(self):
|
||||
print(f"\n\nThe Table is:")
|
||||
print(f"Process\tArrival\tBurst\tWaiting\tCompletedAt\tT.A.T\n")
|
||||
for p in self.table1:
|
||||
p.display()
|
||||
|
||||
def sjf(self):
|
||||
time = 0
|
||||
self.table1 = sorted(self.table,key= lambda p: p.bt) #sorts array based on arrival time
|
||||
for cp in self.table1:
|
||||
cp.ct = cp.bt + time
|
||||
if time:
|
||||
cp.wt = time - cp.at
|
||||
else:
|
||||
cp.wt = 0
|
||||
cp.tat = cp.wt + cp.bt
|
||||
time+= cp.bt
|
||||
|
||||
# Code by Afan Shaikh.
|
||||
tab = Table_class()
|
||||
print("Using sjf!!\n\n")
|
||||
tab.sjf()
|
||||
tab.createTable()
|
||||
@@ -1,109 +0,0 @@
|
||||
# Assignment-A1 - Pass 1 assembler
|
||||
|
||||
try:
|
||||
source = open('source.txt','r')
|
||||
data = source.read()
|
||||
print('File read successfully\n\n')
|
||||
source.seek(0)
|
||||
except FileNotFoundError: #A little bit of exception handling
|
||||
print('\n\n\nFile Not found. Create a source.txt first.\n\n\n ')
|
||||
except IOError:
|
||||
print('There was an IO error')
|
||||
LT_index = 0 #index of LT table
|
||||
ST_index = 0 #index of ST table
|
||||
add = 0 # address in source code
|
||||
MOT = {'STOP': '00','ADD': '01','SUB': '02','MULT': '03','MOVER': '04','MOVEM': '05','COMP': '06','BC': '07','DIV': '08','READ': '09','PRINT': '10','START': '01','END': '02','ORIGIN': '03','LTORG': '05','DS': '01','DC': '02','AREG,': '01','BREG,': '02','EQ':'01'}
|
||||
ST = []
|
||||
code=[]
|
||||
LT=[]
|
||||
MC = []
|
||||
# LT, ST are lists of lists. code= intermediate code table
|
||||
|
||||
|
||||
def classy(text):
|
||||
'''This function will return the class of the word to be inputted in the Intermediate table'''
|
||||
text = text.upper()
|
||||
if text in ['STOP','ADD','SUB', 'MULT','MOVER','MOVEM','COMP','BC','DIV','READ', 'PRINT']:
|
||||
return 'IS'
|
||||
elif text in ['START','END','ORIGIN','LTORG']:
|
||||
return 'AD'
|
||||
elif text in ['DS','DC']:
|
||||
return 'DL'
|
||||
elif text in ['AREG,','BREG,']: return 'RG'
|
||||
elif text in ['EQ']: return 'CC'
|
||||
else: return 'None'
|
||||
|
||||
def handle_start():
|
||||
'''This function gives you the starting address of the code'''
|
||||
line= source.readline()
|
||||
words=line.split()
|
||||
if words[0].upper()=='START':
|
||||
return int(words[1])
|
||||
else:
|
||||
print("No Start Statement! Abort!\n")
|
||||
return 0
|
||||
|
||||
def pass1():
|
||||
add=handle_start()
|
||||
if not add:
|
||||
print("Ending Pass 1 due to Above error.")
|
||||
return
|
||||
global ST_index, LT_index # to modify global variables, use global keyword
|
||||
while True:
|
||||
line=source.readline()# handlestart function reads line 1 and we start from the second line.
|
||||
if not line:
|
||||
break
|
||||
words= line.split()
|
||||
for w in words:
|
||||
w=w.upper()
|
||||
if w[0]=='=':
|
||||
entry=[LT_index,w, add]
|
||||
LT.append(entry)
|
||||
LT_index +=1
|
||||
elif classy(w)== 'None':
|
||||
for term in ST:
|
||||
if w== term[1]: break # I check if the label is already present in ST.
|
||||
else:
|
||||
entry=[ST_index,w, add]
|
||||
ST.append(entry)
|
||||
ST_index +=1
|
||||
add+=1
|
||||
print('LT:')
|
||||
for a in LT:
|
||||
print(a)
|
||||
print('\n\n\nST:')
|
||||
for a in ST:
|
||||
print(a)
|
||||
|
||||
def intermediate():
|
||||
source.seek(0)
|
||||
while True:
|
||||
entry=[]
|
||||
ind = 0
|
||||
line=source.readline()
|
||||
if not line:
|
||||
break
|
||||
words=line.split()
|
||||
for w in words:
|
||||
w=w.upper()
|
||||
if classy(w)!='None': #it is a directive
|
||||
entry.append((classy(w),MOT[w]))
|
||||
elif w[0]== '=': #it is a literal.
|
||||
for a in LT:
|
||||
if a[1]==w:
|
||||
ind = a[0]
|
||||
break
|
||||
entry.append(('L',ind))
|
||||
else: #it is a symbol
|
||||
for a in ST:
|
||||
if a[1]==w:
|
||||
ind = a[0]
|
||||
break
|
||||
entry.append(('S',ind))
|
||||
code.append(entry)
|
||||
print("\nThe Intermediate code is:")
|
||||
for entry in code:
|
||||
print(entry)
|
||||
|
||||
pass1()
|
||||
intermediate()
|
||||
@@ -1,4 +0,0 @@
|
||||
Start 100
|
||||
Label MOVER AREG, =5
|
||||
add areg, =999
|
||||
sub breg, x
|
||||
@@ -1,35 +0,0 @@
|
||||
#include <jni.h>
|
||||
#include <stdio.h>
|
||||
#include "A3.h"
|
||||
|
||||
// NOTE: The contents of this file can be referenced from A3.h which is the generated header file
|
||||
// Refer explanation for more info: https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/EXPLANATION.md
|
||||
|
||||
JNIEXPORT jint JNICALL Java_A3_add(JNIEnv *env, jobject obj, jint a, jint b) { // Function for addition
|
||||
jint result = a + b;
|
||||
printf("\n%d + %d = %d\n", a, b, result);
|
||||
return result; // Return the result
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_A3_sub(JNIEnv *env, jobject obj, jint a, jint b) { // Function for subtraction
|
||||
jint result = a - b;
|
||||
printf("\n%d - %d = %d\n", a, b, result);
|
||||
return result; // Return the result
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_A3_mul(JNIEnv *env, jobject obj, jint a, jint b) { // Function for multiplication
|
||||
jint result = a * b;
|
||||
printf("\n%d * %d = %d\n", a, b, result);
|
||||
return result; // Return the result
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_A3_div(JNIEnv *env, jobject obj, jint a, jint b) { // Function for division
|
||||
if (b == 0) {
|
||||
printf("Error: Division by zero.\n");
|
||||
return 0; // Return 0 or handle error appropriately
|
||||
}
|
||||
jint result = a / b;
|
||||
printf("\n%d / %d = %d\n", a, b, result);
|
||||
return result; // Return the result
|
||||
}
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
// WARNING!!!
|
||||
// THIS FILE IS INCLUDED ONLY FOR REFERENCE
|
||||
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||
#include <jni.h>
|
||||
/* Header for class A3 */
|
||||
|
||||
#ifndef _Included_A3
|
||||
#define _Included_A3
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/*
|
||||
* Class: A3
|
||||
* Method: add
|
||||
* Signature: (II)I
|
||||
*/
|
||||
JNIEXPORT jint JNICALL Java_A3_add
|
||||
(JNIEnv *, jobject, jint, jint);
|
||||
|
||||
/*
|
||||
* Class: A3
|
||||
* Method: sub
|
||||
* Signature: (II)I
|
||||
*/
|
||||
JNIEXPORT jint JNICALL Java_A3_sub
|
||||
(JNIEnv *, jobject, jint, jint);
|
||||
|
||||
/*
|
||||
* Class: A3
|
||||
* Method: mul
|
||||
* Signature: (II)I
|
||||
*/
|
||||
JNIEXPORT jint JNICALL Java_A3_mul
|
||||
(JNIEnv *, jobject, jint, jint);
|
||||
|
||||
/*
|
||||
* Class: A3
|
||||
* Method: div
|
||||
* Signature: (II)I
|
||||
*/
|
||||
JNIEXPORT jint JNICALL Java_A3_div
|
||||
(JNIEnv *, jobject, jint, jint);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -1,67 +0,0 @@
|
||||
// Importing basic stuff
|
||||
import java.io.*; // Used for I/O operations
|
||||
import java.util.*; // Contains basic utilities
|
||||
|
||||
class A3 {
|
||||
// Class name has to be same as file name for Java
|
||||
|
||||
static {
|
||||
// Used for loading the .so (on Linux) or .dll (on Windows) file when running
|
||||
// This is the main so called "dynamic library"
|
||||
System.loadLibrary("A3");
|
||||
}
|
||||
|
||||
// Function declaration
|
||||
// private indicates the function is private, duh!
|
||||
// Use of native indicates the function body will be written in a language other than Java, such as C/C++
|
||||
private native int add(int a, int b); // For addition
|
||||
private native int sub(int a, int b); // For subtraction
|
||||
private native int mul(int a, int b); // For multiplication
|
||||
private native int div(int a, int b); // For division
|
||||
|
||||
public static void main(String[] args) { // the main function
|
||||
Scanner sc = new Scanner(System.in); // For taking input
|
||||
|
||||
int a, b;// Declaring variables for calculation
|
||||
int choice = 0; // Declaring variable for switch-case
|
||||
|
||||
// Take input for a and b values
|
||||
System.out.print("\nValue of a:\t");
|
||||
a = sc.nextInt();
|
||||
System.out.print("\nValue of b:\t");
|
||||
b = sc.nextInt();
|
||||
|
||||
// Main menu
|
||||
while (true) {
|
||||
System.out.println("----- MAIN MENU -----");
|
||||
System.out.println("1 -> Addition");
|
||||
System.out.println("2 -> Subtraction");
|
||||
System.out.println("3 -> Multiplication");
|
||||
System.out.println("4 -> Division");
|
||||
System.out.println("5 -> Exit");
|
||||
System.out.println("Choose an option:\t");
|
||||
choice = sc.nextInt();
|
||||
|
||||
switch (choice) {
|
||||
case 1:
|
||||
System.out.println("Result: " + new A3().add(a, b));
|
||||
break;
|
||||
case 2:
|
||||
System.out.println("Result: " + new A3().sub(a, b));
|
||||
break;
|
||||
case 3:
|
||||
System.out.println("Result: " + new A3().mul(a, b));
|
||||
break;
|
||||
case 4:
|
||||
System.out.println("Result: " + new A3().div(a, b));
|
||||
break;
|
||||
case 5:
|
||||
System.out.println("## END OF CODE");
|
||||
System.exit(0);
|
||||
default:
|
||||
System.out.println("Please choose a valid option.");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
# Explanation
|
||||
|
||||
This file contains explanation for dynamic linking library program (Assignment-A3)
|
||||
|
||||
---
|
||||
|
||||
Please note the files referred in this guide:
|
||||
- [A3.java](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/A3.java)
|
||||
- [A3.c](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/A3.c)
|
||||
- [A3.h](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/A3.h)
|
||||
|
||||
---
|
||||
|
||||
- We're using Java for writing the main program.
|
||||
- To demonstrate Dynamic Linking Library (DLL) in Java, we'll be declaring functions in Java and implementing them in C (can be C/C++).
|
||||
- First, we create a Java program `A3.java`,
|
||||
- This is the main Java file containing function definition and the main function.
|
||||
- Functions (add, sub, mul, div) in `A3` class in this file are native functions, meaning their body is written in C/C++ in a different file.
|
||||
- After creating this file, you need to compile it. To do so, run `javac A3.java` (assuming you're already in the directory that contains this file).
|
||||
- Now, we will generate the header file. For this, run `javac -h . A3.java`.
|
||||
- There will be a new file called `A3.h` in your current working directory,
|
||||
- This is the header file.
|
||||
- It contains signatures for native functions we created in the Java file.
|
||||
- Thus, there's **no need to memorized boilerplate in `A3.c`** since the functions defined in that file can be found in the header file. I have included the [A3.h](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/A3.h) file in this folder for reference. Note that it is automatically generated.
|
||||
- Create a new `A3.c` file which is the C program file containing function definitions (for add, sub, mul, div)
|
||||
- Define all the functions (add, sub, mul, div)
|
||||
- Then, we have to compile the C program file, i.e. `A3.c`. For this, run `gcc -shared -o libA3.so -fPIC -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" A3.c`,
|
||||
- `gcc` -> GNU compiler for C program
|
||||
- `-shared` -> tells the compiler to create a shared file (.so) instead of a regular executable file
|
||||
- `-o libA3.so` -> tells the compiler to save the output to `libA3.so` file
|
||||
- `fPIC` -> stands for Position-Independent Code. Needed for creating shared libraries.
|
||||
- `-I"$JAVA_HOME/include"` and `-I"$JAVA_HOME/include/linux"` -> `-I` flag used for specifiying directories to include. Values in double quotes are directories
|
||||
- `A3.c` -> name of the C program file to compile
|
||||
- Lastly, run the program using `java -Djava.library.path=. A3`
|
||||
- `java` -> Loads Java Virtual Machine (JVM)
|
||||
- `-Djava.library.path=.` -> `-D` is used to set a system property. In this case, we’re setting the `java.library.path` (for .so or .dll files) property.
|
||||
- `A3` -> name of the Java class containing the main method
|
||||
|
||||
---
|
||||
@@ -1,69 +0,0 @@
|
||||
## Steps to run this code
|
||||
|
||||
These are the steps to run code for Assignment-A3.
|
||||
|
||||
---
|
||||
|
||||
### Refer [EXPLANATION](https://git.kska.io/sppu-te-comp-content/SystemsProgrammingAndOperatingSystem/src/branch/main/Codes/Group%20A/Assignment-A3/EXPLANATION.md) to understand how everything works.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Tested on Linux and Windows.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
1. open-jdk (version 11 or higher)
|
||||
2. gcc
|
||||
3. Set open-jdk and gcc as environment variables using bin folder in path (For Windows Users only)
|
||||
4. Common sense
|
||||
|
||||
### Steps For Linux
|
||||
|
||||
1. Compile `A3.java`:
|
||||
```shell
|
||||
javac A3.java
|
||||
```
|
||||
|
||||
2. Generate header file:
|
||||
```shell
|
||||
javac -h . A3.java
|
||||
```
|
||||
|
||||
3. Compile C code:
|
||||
```shell
|
||||
gcc -shared -o libA3.so -fPIC -I"$JAVA_HOME/include" -I"$JAVA_HOME/include/linux" A3.c
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> If you get an error saying _"fatal error: jni.h: No such file or directory"_, this might be because you haven't set `$JAVA_HOME` environment variable. Usually JVM stuff is in `/usr/lib/jvm/java-<version>-openjdk-amd64`. To set `JAVA_HOME` environment variable, run: `export $JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64` (for version 17, adjust for your version accordingly.)
|
||||
|
||||
4. Run program:
|
||||
```shell
|
||||
java -Djava.library.path=. A3
|
||||
```
|
||||
### Steps For Windows
|
||||
|
||||
1. Compile `A3.java`:
|
||||
```shell
|
||||
javac A3.java
|
||||
```
|
||||
|
||||
2. Generate header file:
|
||||
```shell
|
||||
javac -h . A3.java
|
||||
```
|
||||
|
||||
3. Set `JAVA_HOME` to the path of your jdk file location:
|
||||
> Note that this is my file location for jdk. It may differ for you.
|
||||
```shell
|
||||
set JAVA_HOME=C:\Program Files\openjdk-23.0.1_windows-x64_bin\jdk-23.0.1
|
||||
```
|
||||
|
||||
4. Compile C code:
|
||||
```shell
|
||||
gcc -shared -o A3.dll -fPIC -I"%JAVA_HOME%\include" -I"%JAVA_HOME%\include\win32" A3.c
|
||||
```
|
||||
|
||||
5. Run program:
|
||||
```shell
|
||||
java -Djava.library.path=. A3
|
||||
```
|
||||
@@ -1,100 +0,0 @@
|
||||
# Assignment-A2 - Two-pass macro processor code in Python
|
||||
|
||||
# BEGINNING OF CODE
|
||||
# Required databases
|
||||
macro_definition_table = {} # Storing all macro definitions with their names
|
||||
macro_name_table = {} # Storing macro names and their index
|
||||
##########################################################################
|
||||
def process_pass1(source_code):
|
||||
mdt_index = 0
|
||||
macro_definition = []
|
||||
current_macro_name = None
|
||||
inside_macro = False
|
||||
|
||||
for line in source_code:
|
||||
tokens = line.strip().split() # store each word of the line of source code
|
||||
|
||||
if (not tokens): # skips blank lines
|
||||
continue
|
||||
|
||||
if (tokens[0] == 'MACRO'): # beginning of macro definition
|
||||
inside_macro = True
|
||||
continue
|
||||
|
||||
if (inside_macro == True and tokens[0] == 'MEND'): # if end of macro is reached
|
||||
inside_macro = False
|
||||
macro_definition_table[current_macro_name] = macro_definition[:]
|
||||
macro_name_table[current_macro_name] = mdt_index
|
||||
mdt_index += len(macro_definition)
|
||||
macro_definition = []
|
||||
current_macro_name = None
|
||||
continue
|
||||
|
||||
if (inside_macro == True): # processing contents of macro
|
||||
if (not current_macro_name):
|
||||
current_macro_name = tokens[0]
|
||||
macro_definition.append(line.strip())
|
||||
##########################################################################
|
||||
def process_pass2(source_code):
|
||||
output = []
|
||||
inside_macro = False
|
||||
|
||||
for line in source_code:
|
||||
tokens = line.strip().split()
|
||||
|
||||
if (not tokens or tokens[0] == 'MACRO'): # skipping spaces, MACRO and MEND keywords
|
||||
inside_macro = True
|
||||
continue
|
||||
elif (tokens[0] == 'MEND'):
|
||||
inside_macro = False
|
||||
continue
|
||||
|
||||
if inside_macro:
|
||||
continue
|
||||
|
||||
macro_name = tokens[0]
|
||||
if macro_name in macro_name_table: # expand macro from source code
|
||||
args = tokens[1:]
|
||||
macro_def = macro_definition_table[macro_name]
|
||||
for expanded_line in macro_def:
|
||||
for i, arg in enumerate(args):
|
||||
expanded_line = expanded_line.replace(f"&ARG{i+1}", arg)
|
||||
output.append(expanded_line)
|
||||
else: # append line if not a macro
|
||||
output.append(line.strip())
|
||||
|
||||
return output
|
||||
##########################################################################
|
||||
def display():
|
||||
print("Macro Name Table (MNT):")
|
||||
for name, index in macro_name_table.items():
|
||||
print(f"Macro Name: {name} | Index: {index}")
|
||||
|
||||
print("Macro Definition Table (MDT):")
|
||||
for name, definition in macro_definition_table.items():
|
||||
print(f"Macro: {name}")
|
||||
for line in definition:
|
||||
print(f"\t{line}")
|
||||
##########################################################################
|
||||
source_code = [
|
||||
"MACRO",
|
||||
"INCR &ARG1",
|
||||
"ADD &ARG1, ONE",
|
||||
"MEND",
|
||||
"MACRO",
|
||||
"DECR &ARG1",
|
||||
"SUB &ARG1, ONE",
|
||||
"MEND",
|
||||
"START",
|
||||
"INCR A",
|
||||
"DECR B",
|
||||
"END"
|
||||
]
|
||||
##########################################################################
|
||||
process_pass1(source_code)
|
||||
display()
|
||||
print("PASS 2:")
|
||||
expanded_code = process_pass2(source_code)
|
||||
for i in expanded_code:
|
||||
print(i)
|
||||
# END OF CODE
|
||||
@@ -0,0 +1,79 @@
|
||||
blocks = [100,500,200,400, 300]
|
||||
processes = [110,50,410]
|
||||
|
||||
def firstfit():
|
||||
block1= blocks.copy()
|
||||
for p in processes:
|
||||
for b in block1:
|
||||
if b>=p:
|
||||
print(f"P {p} allocated to B {b}")
|
||||
block1.pop(block1.index(b))
|
||||
break
|
||||
else: print(f"P {p} not allocated")
|
||||
print(f"Blocks empty: ", block1)
|
||||
|
||||
print(blocks,"\n",processes)
|
||||
print("\n\n FF:")
|
||||
firstfit()
|
||||
|
||||
|
||||
def bestfit():
|
||||
block1= sorted(blocks)
|
||||
for p in processes:
|
||||
for b in block1:
|
||||
if b>=p:
|
||||
print(f"P {p} allocated to B {b}")
|
||||
block1.pop(block1.index(b))
|
||||
break
|
||||
else: print(f"P {p} not allocated")
|
||||
print(f"Blocks empty: ", block1)
|
||||
|
||||
print("\n\n BF:")
|
||||
bestfit()
|
||||
|
||||
'''
|
||||
Common External Q: why tha fuck was worst fit even invented?
|
||||
->coz in bestfit, we have small spaces left in all the blocks.unuseable.
|
||||
But in worstfit, we have one large space in the biggest block. so we can put in one more process if extra.
|
||||
This is called External Fragmentation...
|
||||
so, Worstfit is better than Bestfit
|
||||
Answer by Afan Shaikh'''
|
||||
def worstfit():
|
||||
block1= sorted(blocks, reverse=True)
|
||||
for p in processes:
|
||||
for b in block1:
|
||||
if b>=p:
|
||||
print(f"P {p} allocated to B {b}")
|
||||
block1.pop(block1.index(b))
|
||||
break
|
||||
else: print(f"P {p} not allocated")
|
||||
print(f"Blocks empty: ", block1)
|
||||
|
||||
print("\n\n WF:")
|
||||
worstfit()
|
||||
|
||||
'''
|
||||
NF:
|
||||
You need to know working of NF, before understanding it's code.
|
||||
start is the starting index for current iteration. at end, we do start++
|
||||
the ind= i%n wraps the index around, like a circle.
|
||||
After allocation, I make block=0 to mark allocated. Who tf is gonna cross check?
|
||||
'''
|
||||
def nextfit():
|
||||
start = 0
|
||||
n = len(blocks)
|
||||
for p in processes:
|
||||
for i in range(start, start +n):
|
||||
ind = i % n
|
||||
if blocks[ind] >= p:
|
||||
print(f"P {p} allocated to B {blocks[ind]}")
|
||||
blocks[ind] = 0
|
||||
start = (ind +1 ) % n
|
||||
break
|
||||
else: print(f'P {p} not allocated')
|
||||
a=[x for x in blocks if x>0]
|
||||
print("Blocks empty: ", a)
|
||||
|
||||
|
||||
print("\n\n NF:")
|
||||
nextfit()
|
||||
@@ -1,80 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
struct fcfs
|
||||
{
|
||||
int burst, arrival, id, completion, waiting, turnaround, response;
|
||||
};
|
||||
fcfs meh[30];
|
||||
|
||||
class FCFS
|
||||
{
|
||||
public:
|
||||
int n;
|
||||
void fcfsIn(){
|
||||
cout<<"\nEnter number of processes: ";
|
||||
cin>>n;
|
||||
for(int i = 0; i < n; i++){
|
||||
cout<<"\nEnter arrival time of P"<<i<<": ";
|
||||
cin>>meh[i].arrival;
|
||||
cout<<"\nEnter burst time of P"<<i<<": ";
|
||||
cin>>meh[i].burst;
|
||||
meh[i].id = i;
|
||||
}
|
||||
cout<<"\n | Arrival | Burst\n";
|
||||
for(int j = 0; j < n; j++) {
|
||||
cout<<"P"<<j<<"| "<<meh[j].arrival<<" | "<<meh[j].burst<<"\n";
|
||||
}
|
||||
}
|
||||
|
||||
void process() {
|
||||
cout<<"\nSequence of processes is: ";
|
||||
int currentTime = 0;
|
||||
|
||||
for(int i = 0; i < n; i++){
|
||||
if(currentTime < meh[i].arrival){
|
||||
while(currentTime < meh[i].arrival){
|
||||
cout<<" NULL ";
|
||||
currentTime++;
|
||||
}
|
||||
}
|
||||
|
||||
meh[i].response = currentTime - meh[i].arrival;
|
||||
cout<<"P"<<meh[i].id<<" ";
|
||||
currentTime += meh[i].burst;
|
||||
meh[i].completion = currentTime;
|
||||
meh[i].turnaround = meh[i].completion - meh[i].arrival;
|
||||
meh[i].waiting = meh[i].turnaround - meh[i].burst;
|
||||
}
|
||||
}
|
||||
|
||||
void displayMetrics()
|
||||
{
|
||||
double totalWaiting = 0, totalTurnaround = 0, totalCompletion = 0;
|
||||
|
||||
cout<<"\n\n | Completion time | Waiting time | Turnaround time | Response time\n";
|
||||
for(int j = 0; j < n; j++) {
|
||||
totalWaiting += meh[j].waiting;
|
||||
totalTurnaround += meh[j].turnaround;
|
||||
totalCompletion += meh[j].completion;
|
||||
cout<<"P"<<j<<"| "<<meh[j].completion
|
||||
<<" | "<<meh[j].waiting
|
||||
<<" | "<<meh[j].turnaround
|
||||
<<" | "<<meh[j].response<<"\n";
|
||||
}
|
||||
|
||||
cout<<"\nAverage completion time: "<<totalCompletion/n;
|
||||
cout<<"\nAverage waiting time: "<<totalWaiting/n;
|
||||
cout<<"\nAverage turnaround time: "<<totalTurnaround/n;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
FCFS obj;
|
||||
obj.fcfsIn();
|
||||
obj.process();
|
||||
obj.displayMetrics();
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
#include<iostream>
|
||||
#include<limits.h> // for INT_MAX
|
||||
using namespace std;
|
||||
|
||||
struct sjf {
|
||||
int burst, arrival, id, completion, waiting, turnaround, response, priority;
|
||||
bool active;
|
||||
};
|
||||
|
||||
sjf meh[30];
|
||||
|
||||
class lesgo {
|
||||
public:
|
||||
int n;
|
||||
|
||||
void priorityIn() {
|
||||
cout << "\nEnter number of processes: ";
|
||||
cin >> n;
|
||||
for (int i = 1; i <= n; i++) {
|
||||
cout << "\nEnter arrival time of P" << i << ": ";
|
||||
cin >> meh[i].arrival;
|
||||
cout << "\nEnter burst time of P" << i << ": ";
|
||||
cin >> meh[i].burst;
|
||||
cout << "\nEnter priority of P" << i << ": ";
|
||||
cin >> meh[i].priority;
|
||||
meh[i].id = i;
|
||||
meh[i].active = false;
|
||||
}
|
||||
cout << "\n | Arrival | Burst | Priority\n";
|
||||
for (int j = 1; j <= n; j++) {
|
||||
cout << "P" << j << " | " << meh[j].arrival << " | " << meh[j].burst << " | " << meh[j].priority << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
void priorityProcess() {
|
||||
int k = 0; // Current time
|
||||
int completed = 0; // Number of completed processes
|
||||
|
||||
while (completed < n) {
|
||||
int highestPriority = INT_MAX;
|
||||
int selectedProcess = -1;
|
||||
|
||||
// Find the process with the highest priority (smallest priority number) that has arrived and is not completed
|
||||
for (int i = 1; i <= n; i++) {
|
||||
if (meh[i].arrival <= k && !meh[i].active && meh[i].priority < highestPriority) {
|
||||
highestPriority = meh[i].priority;
|
||||
selectedProcess = i;
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedProcess != -1) {
|
||||
// Mark the process as active
|
||||
meh[selectedProcess].active = true;
|
||||
|
||||
// If the process is starting now, calculate response time
|
||||
if (meh[selectedProcess].response == 0) {
|
||||
meh[selectedProcess].response = k - meh[selectedProcess].arrival;
|
||||
}
|
||||
|
||||
// Execute the process
|
||||
k += meh[selectedProcess].burst;
|
||||
meh[selectedProcess].completion = k;
|
||||
meh[selectedProcess].turnaround = meh[selectedProcess].completion - meh[selectedProcess].arrival;
|
||||
meh[selectedProcess].waiting = meh[selectedProcess].turnaround - meh[selectedProcess].burst;
|
||||
|
||||
completed++;
|
||||
} else {
|
||||
// If no process is ready to run, just increment time
|
||||
k++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void displayMetrics() {
|
||||
double totalWaiting = 0, totalTurnaround = 0, totalCompletion = 0;
|
||||
|
||||
cout << "\n\n | Completion time | Waiting time | Turnaround time | Response time\n";
|
||||
for (int j = 1; j <= n; j++) {
|
||||
totalWaiting += meh[j].waiting;
|
||||
totalTurnaround += meh[j].turnaround;
|
||||
totalCompletion += meh[j].completion;
|
||||
cout << "P" << j << " | " << meh[j].completion
|
||||
<< " | " << meh[j].waiting
|
||||
<< " | " << meh[j].turnaround
|
||||
<< " | " << meh[j].response << "\n";
|
||||
}
|
||||
|
||||
cout << "\nAverage completion time: " << totalCompletion / n;
|
||||
cout << "\nAverage waiting time: " << totalWaiting / n;
|
||||
cout << "\nAverage turnaround time: " << totalTurnaround / n;
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
lesgo obj;
|
||||
obj.priorityIn();
|
||||
obj.priorityProcess();
|
||||
obj.displayMetrics();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
#include<iostream>
|
||||
#include<queue>
|
||||
using namespace std;
|
||||
|
||||
struct Process{
|
||||
int id, burst, arrival, remaining, completion, waiting, turnaround, response;
|
||||
};
|
||||
Process processes[30];
|
||||
|
||||
class RoundRobin{
|
||||
public:
|
||||
int n, timeQuantum;
|
||||
|
||||
void input(){
|
||||
cout<<"\nEnter number of processes: ";
|
||||
cin>>n;
|
||||
for(int i = 0; i < n; i++){
|
||||
cout<<"\nEnter arrival time of P"<<i<<": ";
|
||||
cin>>processes[i].arrival;
|
||||
cout<<"Enter burst time of P"<<i<<": ";
|
||||
cin>>processes[i].burst;
|
||||
processes[i].id = i;
|
||||
processes[i].remaining = processes[i].burst;
|
||||
processes[i].response = -1;
|
||||
}
|
||||
cout<<"\nEnter time quantum: ";
|
||||
cin>>timeQuantum;
|
||||
}
|
||||
|
||||
void process(){
|
||||
int currentTime = 0;
|
||||
queue<int> q;
|
||||
bool inQueue[30] = {false};
|
||||
int completedProcesses = 0;
|
||||
|
||||
for(int i = 0; i < n; i++){
|
||||
if(processes[i].arrival <= currentTime){
|
||||
q.push(i);
|
||||
inQueue[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
while(completedProcesses < n){
|
||||
if(q.empty()){
|
||||
currentTime++;
|
||||
for(int i = 0; i < n; i++){
|
||||
if(!inQueue[i] && processes[i].arrival <= currentTime){
|
||||
q.push(i);
|
||||
inQueue[i] = true;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
int idx = q.front();
|
||||
q.pop();
|
||||
|
||||
if(processes[idx].response == -1){
|
||||
processes[idx].response = currentTime - processes[idx].arrival;
|
||||
}
|
||||
|
||||
if(processes[idx].remaining <= timeQuantum){
|
||||
currentTime += processes[idx].remaining;
|
||||
processes[idx].remaining = 0;
|
||||
processes[idx].completion = currentTime;
|
||||
processes[idx].turnaround = processes[idx].completion - processes[idx].arrival;
|
||||
processes[idx].waiting = processes[idx].turnaround - processes[idx].burst;
|
||||
completedProcesses++;
|
||||
}else{
|
||||
currentTime += timeQuantum;
|
||||
processes[idx].remaining -= timeQuantum;
|
||||
}
|
||||
|
||||
for(int i = 0; i < n; i++){
|
||||
if(!inQueue[i] && processes[i].arrival <= currentTime && processes[i].remaining > 0){
|
||||
q.push(i);
|
||||
inQueue[i] = true;
|
||||
}
|
||||
}
|
||||
|
||||
if(processes[idx].remaining > 0){
|
||||
q.push(idx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void displayMetrics(){
|
||||
double totalWaiting = 0, totalTurnaround = 0, totalCompletion = 0;
|
||||
|
||||
cout<<"\n\n | Completion time | Waiting time | Turnaround time | Response time\n";
|
||||
for(int i = 0; i < n; i++){
|
||||
totalWaiting += processes[i].waiting;
|
||||
totalTurnaround += processes[i].turnaround;
|
||||
totalCompletion += processes[i].completion;
|
||||
cout<<"P"<< processes[i].id<<" | "<<processes[i].completion<<" | "<< processes[i].waiting<<" | "<<processes[i].turnaround<<" | "<<processes[i].response<<"\n";
|
||||
}
|
||||
|
||||
cout<<"\nAverage completion time: "<<totalCompletion/n;
|
||||
cout<<"\nAverage waiting time: "<<totalWaiting/n;
|
||||
cout<<"\nAverage turnaround time: "<<totalTurnaround/n;
|
||||
}
|
||||
};
|
||||
|
||||
int main(){
|
||||
RoundRobin rr;
|
||||
rr.input();
|
||||
rr.process();
|
||||
rr.displayMetrics();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
struct sjf{
|
||||
int id, arr, bur, comp, turn, wait, orgBur;
|
||||
};
|
||||
sjf meh[30];
|
||||
|
||||
class SJF{
|
||||
public:
|
||||
int n;
|
||||
void getIn()
|
||||
{
|
||||
cout<<"Enter number of processes: ";
|
||||
cin>>n;
|
||||
for(int i = 0; i < n; i++){
|
||||
cout<<"\nEnter arrival time for process "<<i<<": ";
|
||||
cin>>meh[i].arr;
|
||||
cout<<"Enter burst time for process "<<i<<": ";
|
||||
cin>>meh[i].bur;
|
||||
meh[i].orgBur = meh[i].bur;
|
||||
meh[i].id = i;
|
||||
}
|
||||
}
|
||||
|
||||
void process()
|
||||
{
|
||||
int k = 0;
|
||||
int completed = 0;
|
||||
cout<<"\nSequence of processes is: ";
|
||||
while(completed < n){
|
||||
int burst = 999;
|
||||
int idd = -1;
|
||||
for(int i = 0; i < n; i++){
|
||||
if(meh[i].arr <= k && meh[i].bur > 0){
|
||||
if(meh[i].bur < burst){
|
||||
burst = meh[i].bur;
|
||||
idd = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(idd != -1){
|
||||
cout<<"P"<<idd<<" ";
|
||||
k++;
|
||||
meh[idd].bur--;
|
||||
if(meh[idd].bur == 0){
|
||||
meh[idd].comp = k;
|
||||
meh[idd].turn = meh[idd].comp - meh[idd].arr;
|
||||
meh[idd].wait = meh[idd].turn - meh[idd].orgBur;
|
||||
completed++;
|
||||
}
|
||||
} else{
|
||||
k++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void display()
|
||||
{
|
||||
double turn = 0, comp = 0, wait = 0;
|
||||
cout<<"\n Completed | Waiting | Turnaround |";
|
||||
for(int i = 0; i < n; i++){
|
||||
turn += meh[i].turn;
|
||||
wait += meh[i].wait;
|
||||
comp += meh[i].comp;
|
||||
cout<<"\nP"<<i<<"| "<<meh[i].comp<<" | "<<meh[i].wait<<" | "<<meh[i].turn;
|
||||
}
|
||||
|
||||
cout<<"\n\nAvg completion time: "<<comp/n;
|
||||
cout<<"\nAvg turnaround time: "<<turn/n;
|
||||
cout<<"\nAvg waiting time: "<<wait/n;
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
SJF ob;
|
||||
ob.getIn();
|
||||
ob.process();
|
||||
ob.display();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
// Assignment A4 - (MUTEX AND SEMAPHORE)
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
class Synchronization {
|
||||
int a[10]; // Increased buffer size to 10
|
||||
int mutex;
|
||||
int empty;
|
||||
int full;
|
||||
int in;
|
||||
int out;
|
||||
|
||||
void wait(int &x) {
|
||||
if (x > 0) x--;
|
||||
}
|
||||
|
||||
void signal(int &x) {
|
||||
x++;
|
||||
}
|
||||
|
||||
public:
|
||||
Synchronization() : mutex(1), empty(10), full(0), in(0), out(0) {}
|
||||
|
||||
void producer() {
|
||||
if (empty > 0 && mutex == 1) {
|
||||
wait(empty);
|
||||
wait(mutex);
|
||||
cout << "Data to be produced: ";
|
||||
int data;
|
||||
cin >> data;
|
||||
a[in] = data;
|
||||
in = (in + 1) % 10; // Update for new buffer size
|
||||
signal(mutex);
|
||||
signal(full);
|
||||
} else {
|
||||
cout << "Buffer is full, cannot produce!" << endl;
|
||||
}
|
||||
}
|
||||
|
||||
void consumer() {
|
||||
if (full > 0 && mutex == 1) {
|
||||
wait(full);
|
||||
wait(mutex);
|
||||
cout << "Data consumed is: " << a[out] << endl; // Show consumed data
|
||||
out = (out + 1) % 10; // Update for new buffer size
|
||||
signal(mutex);
|
||||
signal(empty);
|
||||
} else {
|
||||
cout << "Buffer is empty, cannot consume!" << endl;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
int fchoice;
|
||||
Synchronization s;
|
||||
do {
|
||||
cout << "1. Producer\n2. Consumer\n3. Exit" << endl;
|
||||
cout << "Enter your choice: ";
|
||||
cin >> fchoice;
|
||||
switch (fchoice) {
|
||||
case 1: s.producer(); break;
|
||||
case 2: s.consumer(); break;
|
||||
case 3: break;
|
||||
default: cout << "Invalid choice!" << endl; break;
|
||||
}
|
||||
} while (fchoice != 3);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int blocks[] = {100, 500, 200, 300, 600};
|
||||
int processes[] = {212, 417, 112, 426};
|
||||
int blkSize = sizeof(blocks) / sizeof(blocks[0]);
|
||||
int prSize = sizeof(processes) / sizeof(processes[0]);
|
||||
|
||||
void FirstFit() {
|
||||
cout<<endl<<"FIRST FIT:";
|
||||
for (int i=0; i<prSize; i++) {
|
||||
bool check = false;
|
||||
for(int j=0; j<blkSize; j++) {
|
||||
if ((blocks[j] - processes[i] >= 0)) {
|
||||
blocks[j] -= processes[i];
|
||||
check = true;
|
||||
cout<<endl<<"Process "<<processes[i]<<" has been allocated to block "<<j+1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (check == false) {
|
||||
cout<<endl<<"Process "<<processes[i]<<" has not been allocated.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void NextFit() {
|
||||
int j = 0;
|
||||
cout<<endl<<"NEXT FIT:";
|
||||
for (int i=0; i<prSize; i++) {
|
||||
bool check = false;
|
||||
for (int k=0; k<blkSize; k++) {
|
||||
if ((blocks[j] - processes[i]) >= 0) {
|
||||
blocks[j] = blocks[j] - processes[i];
|
||||
cout<<endl<<"Process "<<processes[i]<<" has been allocated to block "<<j+1;
|
||||
check = true;
|
||||
break;
|
||||
}
|
||||
j = (j + 1) % blkSize;
|
||||
}
|
||||
if (check == false) {
|
||||
cout<<endl<<"Process "<<processes[i]<<" has not been allocated.";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BestFit() {
|
||||
cout<<endl<<"BEST FIT:";
|
||||
for (int i=0; i<prSize; i++) {
|
||||
bool check = false;
|
||||
int k, store = 999;
|
||||
for (int j=0; j<blkSize; j++) {
|
||||
if ((blocks[j] - processes[i]) >= 0 && (blocks[j] - processes[i]) < store) {
|
||||
k = j + 1;
|
||||
store = blocks[j] - processes[i];
|
||||
check = true;
|
||||
}
|
||||
}
|
||||
if (check == false) {
|
||||
cout<<endl<<"Process "<<processes[i]<<" was not allocated to any block.";
|
||||
}
|
||||
else {
|
||||
blocks[k - 1] -= processes[i];
|
||||
cout<<endl<<"Process "<<processes[i]<<" was allocated to block "<<k;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void WorstFit() {
|
||||
cout<<endl<<"WORST FIT:";
|
||||
for (int i=0; i<prSize; i++) {
|
||||
bool check = false;
|
||||
int k, store = -1;
|
||||
for (int j=0; j<blkSize; j++) {
|
||||
if ((blocks[j] - processes[i] >= 0 && (blocks[j] - processes[i] > store))) {
|
||||
k = j + 1;
|
||||
store = blocks[j] - processes[i];
|
||||
check = true;
|
||||
}
|
||||
}
|
||||
if (check == false) {
|
||||
cout<<endl<<"Process "<<processes[i]<<" was not allocated to any block.";
|
||||
}
|
||||
else {
|
||||
blocks[k - 1] -= processes[i];
|
||||
cout<<endl<<"Process "<<processes[i]<<" was allocated to block "<<k;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main () {
|
||||
// ONLY RUN ONE FUNCTION AT A TIME.
|
||||
// FirstFit();
|
||||
// NextFit();
|
||||
BestFit();
|
||||
// WorstFit();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
// Assignment-B7 - Page Replacement in C++ (LRU + Optimal)
|
||||
// BEGINNING OF CODE
|
||||
#include <cmath>
|
||||
#include <complex>
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int refString[] = {0, 2, 1, 6, 4, 0, 1, 0, 3, 1, 2, 1};
|
||||
int window = 0, hit = 0, miss = 0, currentPages[4], lastUsed[40];
|
||||
int len = sizeof(refString) / sizeof(refString[0]);
|
||||
|
||||
int findLRU() {
|
||||
int min_index = 0;
|
||||
for (int i=1; i<window; i++) {
|
||||
if (lastUsed[i] < lastUsed[min_index]) {
|
||||
min_index = i;
|
||||
}
|
||||
}
|
||||
return min_index;
|
||||
}
|
||||
|
||||
void LRU() {
|
||||
for (int i=0; i<window; i++) {
|
||||
currentPages[i] = -1;
|
||||
lastUsed[i] = -1;
|
||||
}
|
||||
|
||||
for (int i=0; i<len; i++) {
|
||||
bool hitFlag = false;
|
||||
for (int j=0; j<window; j++) {
|
||||
if (currentPages[j] == refString[i]) {
|
||||
hit++;
|
||||
hitFlag = true;
|
||||
lastUsed[j] = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hitFlag == false) {
|
||||
miss++;
|
||||
bool emptyFound = false;
|
||||
for (int j=0; j<window; j++) {
|
||||
if (currentPages[j] == -1) {
|
||||
emptyFound = true;
|
||||
currentPages[j] = refString[i];
|
||||
lastUsed[j] = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (emptyFound == false) {
|
||||
int lru_index = findLRU();
|
||||
currentPages[lru_index] = refString[i];
|
||||
lastUsed[lru_index] = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
cout<<endl<<"----- LRU ------";
|
||||
cout<<endl<<"Number of hits: "<<hit;
|
||||
cout<<endl<<"Number of misses: "<<miss;
|
||||
}
|
||||
|
||||
int findOptimal(int current_index) {
|
||||
int max_index = -1, farthest = current_index;
|
||||
for (int i=0; i<window; i++) {
|
||||
int j;
|
||||
for (j=current_index+1; j<len; j++) {
|
||||
if (currentPages[i] == refString[j]) {
|
||||
if (j > farthest) {
|
||||
farthest = j;
|
||||
max_index = i;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (j == len) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return max_index;
|
||||
}
|
||||
|
||||
void Optimal() {
|
||||
hit = 0;
|
||||
miss = 0;
|
||||
|
||||
for (int i=0; i<window; i++) {
|
||||
currentPages[i] = -1;
|
||||
}
|
||||
|
||||
for (int i=0; i<len; i++) {
|
||||
bool hitFlag = false;
|
||||
for (int j=0; j<window; j++) {
|
||||
if (currentPages[j] == refString[i]) {
|
||||
hit++;
|
||||
hitFlag = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hitFlag == false) {
|
||||
miss++;
|
||||
bool emptyFound = false;
|
||||
for (int j=0; j<window; j++) {
|
||||
if (currentPages[j] == -1) {
|
||||
emptyFound = true;
|
||||
currentPages[j] = refString[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (emptyFound == false) {
|
||||
int optimal_index = findOptimal(i);
|
||||
currentPages[optimal_index] = refString[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
cout<<endl<<"----- OPTIMAL -----";
|
||||
cout<<endl<<"Number of hits: "<<hit;
|
||||
cout<<endl<<"Number of misses: "<<miss;
|
||||
}
|
||||
|
||||
void display() {
|
||||
cout<<endl<<"Current pages are:\t";
|
||||
for (int i=0; i<window; i++) {
|
||||
cout<<currentPages[i]<<" ";
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
|
||||
int main() {
|
||||
cout<<endl<<"Enter window size:\t";
|
||||
cin>>window;
|
||||
LRU();
|
||||
display();
|
||||
Optimal();
|
||||
display();
|
||||
}
|
||||
// END OF CODE
|
||||
@@ -0,0 +1,88 @@
|
||||
class pass1macro:
|
||||
def __init__(self,filename):
|
||||
self.filename = filename
|
||||
self.lines = []
|
||||
with open(filename, "r") as input_file:
|
||||
for line in input_file:
|
||||
self.lines.append(line.rstrip().split(" "))
|
||||
def pass1(self):
|
||||
self.mdt = []
|
||||
self.mnt = {}
|
||||
self.pntab = {}
|
||||
self.kptab = {}
|
||||
self.kptr = 100
|
||||
self.mdtptr = 0
|
||||
isInMacro = False
|
||||
i = 0
|
||||
macro_name = ""
|
||||
while i < len(self.lines):
|
||||
if self.lines[i][0] == "MACRO" and not isInMacro:
|
||||
isInMacro = True
|
||||
i += 1
|
||||
macro_name = self.lines[i][0]
|
||||
params = self.lines[i][1].split(",")
|
||||
startptr = self.kptr
|
||||
self.pntab[macro_name] = {}
|
||||
kp = 0
|
||||
for param in params:
|
||||
if "=" in param:
|
||||
kp += 1
|
||||
key = param.split("=")[0]
|
||||
if len(param.split("=")) == 2:
|
||||
val = param.split("=")[1]
|
||||
else:
|
||||
val = ""
|
||||
self.kptab[self.kptr] = (key, val)
|
||||
self.kptr += 1
|
||||
self.pntab[macro_name][len(self.pntab[macro_name]) + 1] = param.split("=")[0]
|
||||
self.mnt[macro_name] = (len(self.pntab[macro_name])-kp, kp, self.mdtptr, startptr)
|
||||
elif self.lines[i][0] == "MEND" and isInMacro:
|
||||
macro_name = ""
|
||||
isInMacro = False
|
||||
self.mdt.append(self.lines[i][0])
|
||||
self.mdtptr += 1elif isInMacro:
|
||||
inst = " ".join(self.lines[i])
|
||||
for key in self.pntab[macro_name]:
|
||||
inst = inst.replace(self.pntab[macro_name][key], f"(P,{key})")
|
||||
self.mdt.append(inst)
|
||||
self.mdtptr += 1
|
||||
i += 1
|
||||
print("Macro Name Table:")
|
||||
# print("Name PP KP MDTP KPDTP")
|
||||
# for key,val in self.mnt.items():
|
||||
# print(f"{key} {val[0]} {val[1]} {val[2] }")
|
||||
print(self.mnt)
|
||||
print("Keyword Parameter Name Table:")
|
||||
print(self.kptab)
|
||||
print("Parameter Name Table:")
|
||||
print(self.pntab)
|
||||
print("Macro Definition Table:")
|
||||
print(self.mdt)
|
||||
obj = pass1macro("prog1.asm")
|
||||
obj.pass1()
|
||||
Testcase:
|
||||
MACRO
|
||||
ONE &O,&N,&E=AREG
|
||||
MOVER &E,&O
|
||||
ADD &E,&N
|
||||
MOVEM &E,&O
|
||||
MEND
|
||||
MACRO
|
||||
TWO &T,&W,&O=DREG
|
||||
MOVER &O,&T
|
||||
ADD &O,&W
|
||||
MOVEM &O,&T
|
||||
MEND
|
||||
START
|
||||
READ O
|
||||
READ T
|
||||
ONE O,9
|
||||
TWO T,7
|
||||
STOP
|
||||
O DS 1
|
||||
T DS 1
|
||||
END
|
||||
|
||||
|
||||
|
||||
Output:
|
||||
@@ -0,0 +1,202 @@
|
||||
INPUT FILES:
|
||||
mnt.txt
|
||||
ONE 2 1 1 1
|
||||
TWO 2 1 5 2
|
||||
mdt.txt
|
||||
MOVER (P,3) (P,1)
|
||||
ADD (P,3) (P,2)
|
||||
MOVEM (P,3) (P,1)
|
||||
MEND
|
||||
MOVER (P,3) (P,1)
|
||||
ADD (P,3) (P,2)
|
||||
MOVEM (P,3) (P,1)
|
||||
MOVER CREG, (P,1)
|
||||
ADD CREG,9
|
||||
MOVEM CREG, (P,1)
|
||||
MEND
|
||||
ir.txt
|
||||
START
|
||||
READ O
|
||||
READ T
|
||||
TWO T, 7
|
||||
PRINT O
|
||||
PRINT T
|
||||
STOP
|
||||
O DS 1
|
||||
T DS 1
|
||||
END
|
||||
kpdt.txt
|
||||
1 E AREG
|
||||
2 O DREG
|
||||
CODE:
|
||||
package macroP2;
|
||||
import java.io.BufferedReader;import
|
||||
import
|
||||
import
|
||||
import
|
||||
import
|
||||
java.io.FileReader;
|
||||
java.io.FileWriter;
|
||||
java.io.IOException;
|
||||
java.util.HashMap;
|
||||
java.util.Vector;
|
||||
public class macrop2 {
|
||||
public static void main (String[] args) throws IOException {
|
||||
BufferedReader mntb=new BufferedReader(new FileReader("mnt.txt"));
|
||||
BufferedReader mdtb=new BufferedReader(new FileReader("mdt.txt"));
|
||||
BufferedReader kpdtb=new BufferedReader(new FileReader("kpdt.txt"));
|
||||
BufferedReader irb=new BufferedReader(new FileReader("ir.txt"));
|
||||
FileWriter fr=new FileWriter("pass2.txt");
|
||||
HashMap<String,MNTEntry>mnt=new HashMap<String,MNTEntry>();
|
||||
HashMap<Integer,String>aptab=new HashMap<Integer,String>();
|
||||
HashMap<String,Integer>aptabinverse=new HashMap<String,Integer>();
|
||||
Vector<String>mdt=new Vector<String>();
|
||||
Vector<String>kpdt=new Vector<String>();
|
||||
String line;
|
||||
int mdtp,kpdtp,pp,kp,paramNo;
|
||||
while((line=mdtb.readLine())!=null)
|
||||
{
|
||||
mdt.addElement(line);
|
||||
}
|
||||
while((line=kpdtb.readLine())!=null){
|
||||
kpdt.addElement(line);
|
||||
}
|
||||
while((line=mntb.readLine())!=null){
|
||||
String[] parts=line.split(" ");
|
||||
mnt.put(parts[0], new
|
||||
MNTEntry(parts[0],Integer.parseInt(parts[1]),Integer.parseInt(parts[2]),Integer.pa
|
||||
rseInt(parts[3]),Integer.parseInt(parts[4])));
|
||||
}
|
||||
while((line=irb.readLine())!=null)
|
||||
{
|
||||
String []parts=line.split("\\s+");
|
||||
if(mnt.containsKey(parts[0]))
|
||||
{
|
||||
pp=mnt.get(parts[0]).getpp();
|
||||
kp=mnt.get(parts[0]).getkp();
|
||||
kpdtp=mnt.get(parts[0]).getkpdtp();
|
||||
mdtp=mnt.get(parts[0]).getmdtp();
|
||||
paramNo=1;
|
||||
for(int i=0;i<pp;i++)
|
||||
{
|
||||
parts[paramNo]=parts[paramNo].replace(",", "");
|
||||
aptab.put(paramNo, parts[paramNo]);
|
||||
aptabinverse.put(parts[paramNo], paramNo);
|
||||
paramNo++;
|
||||
}
|
||||
int j=kpdtp-1;
|
||||
for(int i=0;i<kp;i++)
|
||||
{
|
||||
String temp[]=kpdt.get(j).split(" ");aptab.put(paramNo,temp[1]);
|
||||
aptabinverse.put(temp[0],paramNo);
|
||||
j++;
|
||||
paramNo++;
|
||||
}
|
||||
for(int i=pp+1;i<parts.length;i++) {
|
||||
parts[i]=parts[i].replace(",", "");
|
||||
String []split=parts[i].split("=");
|
||||
String name=split[0].replace("&", "");
|
||||
aptab.put(aptabinverse.get(name),split[1]);
|
||||
paramNo++;
|
||||
}
|
||||
int i=mdtp-1;
|
||||
while(!mdt.get(i).equalsIgnoreCase("MEND"))
|
||||
{
|
||||
String splits[]=mdt.get(i).split(" ");
|
||||
fr.write("+");
|
||||
for(int k=0;k<splits.length;k++)
|
||||
{
|
||||
if(splits[k].contains("(P,"))
|
||||
{
|
||||
splits[k]=splits[k].replaceAll("[^0-9]", "");
|
||||
String
|
||||
value=aptab.get(Integer.parseInt(splits[k]));
|
||||
fr.write(value+"\t");
|
||||
}
|
||||
else
|
||||
{
|
||||
fr.write(splits[k]+"\t");
|
||||
}
|
||||
}
|
||||
fr.write("\n");
|
||||
i++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
}
|
||||
aptab.clear();
|
||||
aptabinverse.clear();
|
||||
fr.write(line+"\n");
|
||||
}
|
||||
fr.close();
|
||||
mntb.close();
|
||||
mdtb.close();
|
||||
kpdtb.close();
|
||||
irb.close();
|
||||
System.out.println("Macro Pass2 done!");
|
||||
}
|
||||
}MNTEntry
|
||||
package macroP2;
|
||||
public class MNTEntry {
|
||||
int pp,kp,mdtp,kpdtp;
|
||||
String S;
|
||||
public MNTEntry(String s,int pp,int kp,int mdtp,int kpdtp) {
|
||||
this.S=s;
|
||||
this.pp=pp;
|
||||
this.kp=kp;
|
||||
this.mdtp=mdtp;
|
||||
this.kpdtp=kpdtp;
|
||||
}
|
||||
public String getname() {
|
||||
return S;
|
||||
}
|
||||
public int getpp() {
|
||||
return pp;
|
||||
}
|
||||
}
|
||||
public void setpp(int data) {
|
||||
this.pp=data;
|
||||
}
|
||||
public void setkp(int data) {
|
||||
this.kp=data;
|
||||
}
|
||||
public void setmdtp(int data) {
|
||||
this.mdtp=data;
|
||||
}
|
||||
public void setkpdtp(int data) {
|
||||
this.kpdtp=data;
|
||||
}
|
||||
public int getkp() {
|
||||
return kp;
|
||||
}
|
||||
public int getmdtp() {
|
||||
return mdtp;
|
||||
}
|
||||
public int getkpdtp() {
|
||||
return kpdtp;
|
||||
}OUTPUT:
|
||||
pass2.txt
|
||||
START
|
||||
READ O
|
||||
READ T
|
||||
+MOVER
|
||||
DREG
|
||||
+ADD DREG 7
|
||||
+MOVEM
|
||||
DREG
|
||||
+MOVER
|
||||
CREG,
|
||||
+ADD CREG,9
|
||||
+MOVEM
|
||||
CREG,
|
||||
PRINT O
|
||||
PRINT T
|
||||
STOP
|
||||
O DS 1
|
||||
T DS 1
|
||||
END
|
||||
T
|
||||
T
|
||||
T
|
||||
T
|
||||
@@ -0,0 +1,118 @@
|
||||
Title : Design suitable data structures and implement Pass 1 of two pass macro-processor
|
||||
CODE
|
||||
#include <iostream>
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
int main(){
|
||||
vector<string> mdt;
|
||||
vector<string> mnt;
|
||||
vector <char> pnt[4];
|
||||
fstream file;
|
||||
int pointer=0;
|
||||
file.open("macro.txt",ios::in);
|
||||
string s = "",str="";
|
||||
int c = 0,r=0,a=-1,b=0;
|
||||
while(getline(file,s)){
|
||||
if(s=="MACRO"){
|
||||
b=1;
|
||||
c=1;
|
||||
a++;
|
||||
continue;
|
||||
}
|
||||
for(auto it:s){
|
||||
if(r==1){
|
||||
int z=0;
|
||||
for(auto x:pnt[a]){
|
||||
if(x==it){
|
||||
z=1;
|
||||
}
|
||||
}
|
||||
if(z==0){
|
||||
pnt[a].push_back(it);
|
||||
}
|
||||
r=0;
|
||||
}
|
||||
if(it=='&'){
|
||||
r=1;}
|
||||
}
|
||||
if(b==1){
|
||||
str="";
|
||||
int v=0;
|
||||
char t=s[v];
|
||||
while(t!=' '){
|
||||
str=str+t;
|
||||
v++;
|
||||
t=s[v];
|
||||
}
|
||||
mnt.push_back(str);
|
||||
b=0;
|
||||
}
|
||||
if(c==1){
|
||||
mdt.push_back(s);
|
||||
}
|
||||
if(s=="MEND"){
|
||||
c=0;
|
||||
}
|
||||
}
|
||||
file.close();
|
||||
cout<<"MDT"<<endl;
|
||||
for(auto it:mdt){
|
||||
cout<<it<<endl;
|
||||
}
|
||||
cout<<endl;
|
||||
for(int i = 0 ; i<=a ; i++){
|
||||
cout<<"PNT"<<i<<endl;
|
||||
for(auto it:pnt[i]){
|
||||
cout<<it<<endl;
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
cout<<"MNT"<<endl;
|
||||
for(auto it:mnt){
|
||||
cout<<it<<endl;
|
||||
}
|
||||
return 0;
|
||||
}Input File : macro.txt
|
||||
MACRO
|
||||
ONE &O,&N,&E=AREG
|
||||
MOVER &E,&O
|
||||
ADD &E,&N
|
||||
MOVEM &E,&O
|
||||
MEND
|
||||
MACRO
|
||||
TWO &T,&W,&O=DREG
|
||||
MOVER &O,&T
|
||||
ADD &O,&W
|
||||
MOVEM &O,&T
|
||||
MEND
|
||||
START
|
||||
READ O
|
||||
READ T
|
||||
ONE O,9
|
||||
TWO T,7
|
||||
STOP
|
||||
O DS 1
|
||||
T DS 1
|
||||
END
|
||||
OUTPUT :
|
||||
MDT
|
||||
ONE &O,&N,&E=AREG
|
||||
MOVER &E,&O
|
||||
ADD &E,&N
|
||||
MOVEM &E,&O
|
||||
MEND
|
||||
TWO &T,&W,&O=DREG
|
||||
MOVER &O,&T
|
||||
ADD &O,&W
|
||||
MOVEM &O,&T
|
||||
MEND
|
||||
PNT0
|
||||
O
|
||||
N
|
||||
E
|
||||
PNT1
|
||||
T
|
||||
WO
|
||||
MNT
|
||||
ONE
|
||||
TWO
|
||||
@@ -0,0 +1,125 @@
|
||||
Design suitable data structures and implement pass1 of a two pass asmbler
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
class TableRow{
|
||||
String name;
|
||||
int index;
|
||||
int address;
|
||||
TableRow(String name,int address){
|
||||
super();
|
||||
this.name=name;
|
||||
this.address=address;
|
||||
this.index=0;
|
||||
}
|
||||
TableRow(String name,int index,int address){
|
||||
this.address=address;
|
||||
this.name=name;
|
||||
this.index=index;
|
||||
}
|
||||
public void setName(String name) {
|
||||
this.name=name;
|
||||
}
|
||||
public void setIndex(int index) {
|
||||
this.index=index;
|
||||
}
|
||||
public void setAddress(int address) {
|
||||
this.address=address;
|
||||
}
|
||||
public String getName() {
|
||||
return this.name;
|
||||
}
|
||||
public int getIndex() {
|
||||
return this.index;
|
||||
}
|
||||
public int getAddress() {
|
||||
return this.address;
|
||||
}
|
||||
}
|
||||
class Initialize{
|
||||
HashMap<String,Integer> AD;
|
||||
HashMap<String,Integer> IS;
|
||||
HashMap<String,Integer> CC;
|
||||
HashMap<String,Integer> RG;
|
||||
HashMap<String,Integer> DL;
|
||||
Initialize(){
|
||||
AD=new HashMap<>();
|
||||
IS=new HashMap<>();CC=new HashMap<>();
|
||||
RG=new HashMap<>();
|
||||
DL=new HashMap<>();
|
||||
AD.put("START",1);
|
||||
AD.put("END",2);
|
||||
AD.put("ORIGIN",3);
|
||||
AD.put("EQU",4);
|
||||
AD.put("LTORG",5);
|
||||
DL.put("DC", 1);
|
||||
DL.put("DS", 2);
|
||||
RG.put("AREG", 1);
|
||||
RG.put("BREG", 2);
|
||||
RG.put("CREG", 3);
|
||||
RG.put("DREG", 4);
|
||||
CC.put("LT", 1);
|
||||
CC.put("LTE",2);
|
||||
CC.put("EQ", 3);
|
||||
CC.put("NEQ",4);
|
||||
CC.put("GT",5);
|
||||
CC.put("GTE",6);
|
||||
IS.put("STOP",0);
|
||||
IS.put("ADD",1);
|
||||
IS.put("SUB",2);
|
||||
IS.put("MULT",3);
|
||||
IS.put("MOVER",4);
|
||||
IS.put("MOVEM",5);
|
||||
IS.put("COMP",6);
|
||||
IS.put("BC",7);
|
||||
IS.put("DIV",8);
|
||||
IS.put("READ", 9);
|
||||
IS.put("PRINT",10);
|
||||
}
|
||||
}
|
||||
class assembler {
|
||||
public static void main(String args[]) throws IOException{
|
||||
BufferedReader br=new BufferedReader(new FileReader("input.txt"));
|
||||
FileWriter pass1=new FileWriter("pass1.txt");
|
||||
FileWriter symtab=new FileWriter("symtab.txt");
|
||||
Initialize in=new Initialize();
|
||||
int symindex=0;
|
||||
int index=0;
|
||||
String line;int flag=0;
|
||||
while((line=br.readLine())!=null) {
|
||||
String parts[]=line.split("\\s+");
|
||||
for(int i=0;i<parts.length;i++) {
|
||||
parts[i]=parts[i].replaceAll(",","");
|
||||
if((in.AD.containsKey(parts[i]))==false) {
|
||||
if((in.CC.containsKey(parts[i]))==false) {
|
||||
if((in.DL.containsKey(parts[i]))==false){
|
||||
if((in.IS.containsKey(parts[i]))==false) {
|
||||
if((in.RG.containsKey(parts[i]))==false) {
|
||||
symtab.write(parts[i]+"\t"+ +
|
||||
+symindex+"\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
symtab.close();
|
||||
br.close();
|
||||
pass1.close();
|
||||
}
|
||||
}
|
||||
INPUT:
|
||||
START 100
|
||||
L1 MOVER AREG, X
|
||||
MOVEM AREG, Y
|
||||
ORIGIN L1+3
|
||||
NEXT ADD AREG, X
|
||||
SUB BREG, Y
|
||||
BC LT, L1
|
||||
ORIGIN NEXT+5
|
||||
MULT CREG, Z
|
||||
STOP
|
||||
X DS 2
|
||||
Y DS 1
|
||||
Z DC '9'
|
||||
END
|
||||
Binary file not shown.
@@ -1,109 +0,0 @@
|
||||
# Assignment A1 - Pass 1 and pass 2 assembler
|
||||
# Example Opcode Table (OPTAB)
|
||||
OPTAB = {
|
||||
"LOAD": "01",
|
||||
"STORE": "02",
|
||||
"ADD": "03",
|
||||
"SUB": "04",
|
||||
"JMP": "05"
|
||||
}
|
||||
|
||||
# Example Assembler Directives
|
||||
DIRECTIVES = ["START", "END", "WORD", "RESW", "RESB"]
|
||||
|
||||
# Symbol Table (SYMTAB) and Intermediate Code
|
||||
SYMTAB = {}
|
||||
intermediate_code = []
|
||||
|
||||
# Pass-I: Generates the symbol table and intermediate code
|
||||
def pass1(input_lines):
|
||||
locctr = 0
|
||||
start_address = 0
|
||||
for line in input_lines:
|
||||
label, opcode, operand = parse_line(line.strip())
|
||||
|
||||
if opcode == "START":
|
||||
start_address = int(operand)
|
||||
locctr = start_address
|
||||
intermediate_code.append((locctr, label, opcode, operand))
|
||||
continue
|
||||
|
||||
# Process label
|
||||
if label:
|
||||
if label in SYMTAB:
|
||||
print(f"Error: Duplicate symbol {label}")
|
||||
SYMTAB[label] = locctr
|
||||
|
||||
# Process opcode
|
||||
if opcode in OPTAB:
|
||||
intermediate_code.append((locctr, label, opcode, operand))
|
||||
locctr += 3 # Assume all instructions are 3 bytes
|
||||
elif opcode in DIRECTIVES:
|
||||
if opcode == "WORD":
|
||||
locctr += 3
|
||||
elif opcode == "RESW":
|
||||
locctr += 3 * int(operand)
|
||||
elif opcode == "RESB":
|
||||
locctr += int(operand)
|
||||
elif opcode == "END":
|
||||
intermediate_code.append((locctr, label, opcode, operand))
|
||||
break
|
||||
else:
|
||||
print(f"Error: Invalid opcode {opcode}")
|
||||
|
||||
return start_address, intermediate_code
|
||||
|
||||
# Parse a line of input (splits line into label, opcode, operand)
|
||||
def parse_line(line):
|
||||
parts = line.split()
|
||||
label = parts[0] if len(parts) == 3 else None
|
||||
opcode = parts[1] if len(parts) == 3 else parts[0]
|
||||
operand = parts[2] if len(parts) == 3 else parts[1] if len(parts) == 2 else None
|
||||
return label, opcode, operand
|
||||
|
||||
# Pass-II: Generates the final machine code
|
||||
def pass2(start_address, intermediate_code):
|
||||
final_code = []
|
||||
for locctr, label, opcode, operand in intermediate_code:
|
||||
if opcode in OPTAB:
|
||||
machine_code = OPTAB[opcode]
|
||||
if operand in SYMTAB:
|
||||
address = format(SYMTAB[operand], '04X') # 4-digit hex address
|
||||
else:
|
||||
address = '0000' # Default if symbol not found
|
||||
final_code.append(f"{locctr:04X} {machine_code} {address}")
|
||||
elif opcode == "WORD":
|
||||
final_code.append(f"{locctr:04X} {int(operand):06X}")
|
||||
elif opcode == "RESW" or opcode == "RESB":
|
||||
final_code.append(f"{locctr:04X} ----")
|
||||
elif opcode == "END":
|
||||
final_code.append(f"{locctr:04X} END")
|
||||
return final_code
|
||||
|
||||
# Main function to read the input file and run both passes
|
||||
def main():
|
||||
# Read the assembly code from input.txt
|
||||
with open("assemblerIP.txt", "r") as file:
|
||||
input_lines = file.readlines()
|
||||
|
||||
# Run Pass-I
|
||||
start_address, intermediate_code = pass1(input_lines)
|
||||
|
||||
# Display Symbol Table and Intermediate Code
|
||||
print("\nPass-I Output:")
|
||||
print("Symbol Table (SYMTAB):", SYMTAB)
|
||||
print("\nIntermediate Code:")
|
||||
for entry in intermediate_code:
|
||||
print(entry)
|
||||
|
||||
# Run Pass-II
|
||||
final_code = pass2(start_address, intermediate_code)
|
||||
|
||||
# Display Final Machine Code
|
||||
print("\nPass-II Output (Final Machine Code):")
|
||||
for code in final_code:
|
||||
print(code)
|
||||
|
||||
# Run the main function
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,8 +0,0 @@
|
||||
COPY START 1000
|
||||
FIRST LOAD ALPHA
|
||||
ADD BETA
|
||||
STORE GAMMA
|
||||
ALPHA WORD 5
|
||||
BETA RESW 1
|
||||
GAMMA RESB 1
|
||||
END FIRST
|
||||
@@ -1,109 +0,0 @@
|
||||
try:
|
||||
source = open('source1.txt', 'r')
|
||||
print("File is read successfully.")
|
||||
source.seek(0)
|
||||
except FileNotFoundError:
|
||||
print('\n\n\nsource2.txt file not found. Create it first!\n\n\n')
|
||||
except IOError:
|
||||
print('The source file has an IO error')
|
||||
|
||||
MDT = [] # Macro Definition Table
|
||||
MNT = [] # Macro Name Table
|
||||
LIT = [] # Literal Table
|
||||
LPT = [] # Literal Pool Table
|
||||
|
||||
|
||||
def macroman(line):
|
||||
name = line.split()[1]
|
||||
entry = []
|
||||
entry.append(line.strip())
|
||||
while True:
|
||||
line = source.readline().upper()
|
||||
if not line:
|
||||
print('No MEND found for: ', name)
|
||||
return
|
||||
if 'MACRO' in line:
|
||||
macroman(line)
|
||||
elif 'MEND' in line:
|
||||
global MDT, MNT
|
||||
entry.append(line.strip())
|
||||
MNT.append([len(MNT) + 1, name, len(MDT) + 1])
|
||||
MDT.extend(entry)
|
||||
return
|
||||
else:
|
||||
entry.append(line.strip())
|
||||
# Check for literals and add to the literal table
|
||||
for word in line.split():
|
||||
if word.startswith('='): # Assuming literals start with '='
|
||||
if word not in LIT:
|
||||
LIT.append(word)
|
||||
|
||||
|
||||
def pass1():
|
||||
global MDT, MNT, LIT
|
||||
while True:
|
||||
line = source.readline().upper()
|
||||
if not line: break
|
||||
if 'MACRO' in line:
|
||||
macroman(line)
|
||||
|
||||
print('\nMNT:')
|
||||
for a in MNT:
|
||||
print(a)
|
||||
|
||||
print('\nMDT:')
|
||||
for i, a in enumerate(MDT, start=1):
|
||||
print(i, ' ', a)
|
||||
|
||||
print('\nLIT:')
|
||||
for i, lit in enumerate(LIT, start=1):
|
||||
print(i, ' ', lit)
|
||||
|
||||
|
||||
pass1()
|
||||
|
||||
|
||||
def inserter(sline, name):
|
||||
global MDT, MNT
|
||||
sline = ''
|
||||
for a in MNT:
|
||||
if a[1] == name:
|
||||
add = a[2]
|
||||
break
|
||||
while True:
|
||||
if 'MEND' in MDT[add]:
|
||||
break
|
||||
sline += MDT[add] + '\n'
|
||||
add += 1
|
||||
return sline
|
||||
|
||||
|
||||
def pass2():
|
||||
source.seek(0)
|
||||
output = open('output.txt', 'w')
|
||||
output.close()
|
||||
output = open('output.txt', 'a+')
|
||||
|
||||
while True:
|
||||
sline = source.readline().upper()
|
||||
if not sline: break
|
||||
for a in MNT:
|
||||
if a[1] in sline and 'MACRO' not in sline:
|
||||
sline = inserter(sline, a[1])
|
||||
d = sline.strip()
|
||||
# Check for literals in the output line
|
||||
for word in d.split():
|
||||
if word.startswith('='):
|
||||
if word not in LPT: # If not already in the literal pool table
|
||||
LPT.append(word)
|
||||
|
||||
if d not in MDT:
|
||||
output.write(sline)
|
||||
|
||||
print('done.')
|
||||
print('\nLPT:')
|
||||
for i, lpt in enumerate(LPT, start=1):
|
||||
print(i, ' ', lpt)
|
||||
|
||||
|
||||
pass2()
|
||||
@@ -1,13 +0,0 @@
|
||||
MACRO FIBO
|
||||
MOVE A, =5
|
||||
ADD A, B
|
||||
MEND
|
||||
|
||||
MACRO SUM
|
||||
ADD A, B
|
||||
MOVE C, =100
|
||||
MEND
|
||||
|
||||
START:
|
||||
FIBO
|
||||
SUM
|
||||
@@ -1,23 +0,0 @@
|
||||
def fcfs_scheduling(processes, n):
|
||||
processes.sort(key=lambda x: x[1])
|
||||
completion_time = 0
|
||||
waiting_time = []
|
||||
turnaround_time = []
|
||||
|
||||
for process in processes:
|
||||
pid, arrival_time, burst_time = process
|
||||
|
||||
if completion_time < arrival_time:
|
||||
completion_time = arrival_time
|
||||
|
||||
completion_time += burst_time
|
||||
turnaround_time.append(completion_time - arrival_time)
|
||||
waiting_time.append(completion_time - arrival_time - burst_time)
|
||||
|
||||
print("\nFCFS Scheduling:")
|
||||
for i, process in enumerate(processes):
|
||||
print(f"Process {process[0]}: Waiting Time = {waiting_time[i]}, Turnaround Time = {turnaround_time[i]}")
|
||||
|
||||
# Input: Process ID, Arrival Time, Burst Time
|
||||
processes = [[1, 0, 5], [2, 1, 3], [3, 2, 8], [4, 3, 6]]
|
||||
fcfs_scheduling(processes, len(processes))
|
||||
@@ -1,23 +0,0 @@
|
||||
def priority_scheduling(processes, n):
|
||||
processes.sort(key=lambda x: (x[2], x[1]))
|
||||
completion_time = 0
|
||||
waiting_time = []
|
||||
turnaround_time = []
|
||||
|
||||
for process in processes:
|
||||
pid, arrival_time, priority, burst_time = process
|
||||
|
||||
if completion_time < arrival_time:
|
||||
completion_time = arrival_time
|
||||
|
||||
completion_time += burst_time
|
||||
turnaround_time.append(completion_time - arrival_time)
|
||||
waiting_time.append(completion_time - arrival_time - burst_time)
|
||||
|
||||
print("\nPriority (Non-Preemptive) Scheduling:")
|
||||
for i, process in enumerate(processes):
|
||||
print(f"Process {process[0]}: Waiting Time = {waiting_time[i]}, Turnaround Time = {turnaround_time[i]}")
|
||||
|
||||
# Input: Process ID, Arrival Time, Priority, Burst Time
|
||||
processes = [[1, 0, 1, 5], [2, 1, 3, 3], [3, 2, 2, 8], [4, 3, 4, 6]]
|
||||
priority_scheduling(processes, len(processes))
|
||||
@@ -1,36 +0,0 @@
|
||||
def round_robin(processes, n, quantum):
|
||||
remaining_time = [bt for _, _, bt in processes]
|
||||
t = 0
|
||||
waiting_time = [0] * n
|
||||
turnaround_time = [0] * n
|
||||
complete = [False] * n
|
||||
|
||||
while True:
|
||||
done = True
|
||||
|
||||
for i in range(n):
|
||||
if remaining_time[i] > 0:
|
||||
done = False
|
||||
|
||||
if remaining_time[i] > quantum:
|
||||
t += quantum
|
||||
remaining_time[i] -= quantum
|
||||
else:
|
||||
t += remaining_time[i]
|
||||
waiting_time[i] = t - processes[i][2] - processes[i][1]
|
||||
remaining_time[i] = 0
|
||||
|
||||
if done:
|
||||
break
|
||||
|
||||
for i in range(n):
|
||||
turnaround_time[i] = processes[i][2] + waiting_time[i]
|
||||
|
||||
print("\nRound Robin (Preemptive) Scheduling:")
|
||||
for i, process in enumerate(processes):
|
||||
print(f"Process {process[0]}: Waiting Time = {waiting_time[i]}, Turnaround Time = {turnaround_time[i]}")
|
||||
|
||||
# Input: Process ID, Arrival Time, Burst Time
|
||||
processes = [[1, 0, 10], [2, 1, 4], [3, 2, 5], [4, 3, 3]]
|
||||
quantum = 2
|
||||
round_robin(processes, len(processes), quantum)
|
||||
@@ -1,48 +0,0 @@
|
||||
import sys
|
||||
|
||||
def sjf_preemptive(processes, n):
|
||||
remaining_time = [bt for _, _, bt in processes]
|
||||
complete = 0
|
||||
t = 0
|
||||
minm = sys.maxsize
|
||||
shortest = 0
|
||||
finish_time = 0
|
||||
check = False
|
||||
waiting_time = [0] * n
|
||||
turnaround_time = [0] * n
|
||||
|
||||
while complete != n:
|
||||
for j in range(n):
|
||||
if processes[j][1] <= t and remaining_time[j] < minm and remaining_time[j] > 0:
|
||||
minm = remaining_time[j]
|
||||
shortest = j
|
||||
check = True
|
||||
|
||||
if not check:
|
||||
t += 1
|
||||
continue
|
||||
|
||||
remaining_time[shortest] -= 1
|
||||
minm = remaining_time[shortest] if remaining_time[shortest] > 0 else sys.maxsize
|
||||
|
||||
if remaining_time[shortest] == 0:
|
||||
complete += 1
|
||||
check = False
|
||||
finish_time = t + 1
|
||||
waiting_time[shortest] = finish_time - processes[shortest][2] - processes[shortest][1]
|
||||
|
||||
if waiting_time[shortest] < 0:
|
||||
waiting_time[shortest] = 0
|
||||
|
||||
t += 1
|
||||
|
||||
for i in range(n):
|
||||
turnaround_time[i] = processes[i][2] + waiting_time[i]
|
||||
|
||||
print("\nSJF (Preemptive) Scheduling:")
|
||||
for i, process in enumerate(processes):
|
||||
print(f"Process {process[0]}: Waiting Time = {waiting_time[i]}, Turnaround Time = {turnaround_time[i]}")
|
||||
|
||||
# Input: Process ID, Arrival Time, Burst Time
|
||||
processes = [[1, 0, 8], [2, 1, 4], [3, 2, 9], [4, 3, 5]]
|
||||
sjf_preemptive(processes, len(processes))
|
||||
@@ -1,28 +0,0 @@
|
||||
def best_fit(memory_blocks, process_sizes):
|
||||
allocation = [-1] * len(process_sizes)
|
||||
|
||||
for i in range(len(process_sizes)):
|
||||
best_idx = -1
|
||||
best_size = float('inf')
|
||||
|
||||
for j in range(len(memory_blocks)):
|
||||
if memory_blocks[j] >= process_sizes[i] and memory_blocks[j] - process_sizes[i] < best_size:
|
||||
best_size = memory_blocks[j] - process_sizes[i]
|
||||
best_idx = j
|
||||
|
||||
if best_idx != -1:
|
||||
allocation[i] = best_idx
|
||||
memory_blocks[best_idx] -= process_sizes[i]
|
||||
|
||||
print("\nBest Fit Allocation:")
|
||||
for i in range(len(process_sizes)):
|
||||
if allocation[i] != -1:
|
||||
print(f"Process {i+1} allocated to Block {allocation[i]+1}")
|
||||
else:
|
||||
print(f"Process {i+1} not allocated")
|
||||
|
||||
# Example Memory Blocks and Process Sizes
|
||||
memory_blocks = [100, 500, 200, 300, 600]
|
||||
process_sizes = [212, 417, 112, 426]
|
||||
|
||||
best_fit(memory_blocks, process_sizes)
|
||||
@@ -1,22 +0,0 @@
|
||||
def first_fit(memory_blocks, process_sizes):
|
||||
allocation = [-1] * len(process_sizes)
|
||||
|
||||
for i in range(len(process_sizes)):
|
||||
for j in range(len(memory_blocks)):
|
||||
if memory_blocks[j] >= process_sizes[i]:
|
||||
allocation[i] = j
|
||||
memory_blocks[j] -= process_sizes[i]
|
||||
break
|
||||
|
||||
print("\nFirst Fit Allocation:")
|
||||
for i in range(len(process_sizes)):
|
||||
if allocation[i] != -1:
|
||||
print(f"Process {i+1} allocated to Block {allocation[i]+1}")
|
||||
else:
|
||||
print(f"Process {i+1} not allocated")
|
||||
|
||||
# Example Memory Blocks and Process Sizes
|
||||
memory_blocks = [100, 500, 200, 300, 600]
|
||||
process_sizes = [212, 417, 112, 426]
|
||||
|
||||
first_fit(memory_blocks, process_sizes)
|
||||
@@ -1,25 +0,0 @@
|
||||
def next_fit(memory_blocks, process_sizes):
|
||||
allocation = [-1] * len(process_sizes)
|
||||
next_index = 0
|
||||
|
||||
for i in range(len(process_sizes)):
|
||||
while next_index < len(memory_blocks):
|
||||
if memory_blocks[next_index] >= process_sizes[i]:
|
||||
allocation[i] = next_index
|
||||
memory_blocks[next_index] -= process_sizes[i]
|
||||
next_index = (next_index + 1) % len(memory_blocks) # Move to next block
|
||||
break
|
||||
next_index += 1
|
||||
|
||||
print("\nNext Fit Allocation:")
|
||||
for i in range(len(process_sizes)):
|
||||
if allocation[i] != -1:
|
||||
print(f"Process {i+1} allocated to Block {allocation[i]+1}")
|
||||
else:
|
||||
print(f"Process {i+1} not allocated")
|
||||
|
||||
# Example Memory Blocks and Process Sizes
|
||||
memory_blocks = [100, 500, 200, 300, 600]
|
||||
process_sizes = [212, 417, 112, 426]
|
||||
|
||||
next_fit(memory_blocks, process_sizes)
|
||||
@@ -1,28 +0,0 @@
|
||||
def worst_fit(memory_blocks, process_sizes):
|
||||
allocation = [-1] * len(process_sizes)
|
||||
|
||||
for i in range(len(process_sizes)):
|
||||
worst_idx = -1
|
||||
worst_size = -1
|
||||
|
||||
for j in range(len(memory_blocks)):
|
||||
if memory_blocks[j] >= process_sizes[i] and memory_blocks[j] > worst_size:
|
||||
worst_size = memory_blocks[j]
|
||||
worst_idx = j
|
||||
|
||||
if worst_idx != -1:
|
||||
allocation[i] = worst_idx
|
||||
memory_blocks[worst_idx] -= process_sizes[i]
|
||||
|
||||
print("\nWorst Fit Allocation:")
|
||||
for i in range(len(process_sizes)):
|
||||
if allocation[i] != -1:
|
||||
print(f"Process {i+1} allocated to Block {allocation[i]+1}")
|
||||
else:
|
||||
print(f"Process {i+1} not allocated")
|
||||
|
||||
# Example Memory Blocks and Process Sizes
|
||||
memory_blocks = [100, 500, 200, 300, 600]
|
||||
process_sizes = [212, 417, 112, 426]
|
||||
|
||||
worst_fit(memory_blocks, process_sizes)
|
||||
@@ -1,31 +0,0 @@
|
||||
class LRU:
|
||||
def __init__(self, capacity):
|
||||
self.capacity = capacity
|
||||
self.cache = {}
|
||||
self.order = []
|
||||
|
||||
def refer(self, page):
|
||||
if page not in self.cache:
|
||||
if len(self.cache) >= self.capacity:
|
||||
lru_page = self.order.pop(0) # Remove least recently used page
|
||||
del self.cache[lru_page]
|
||||
else:
|
||||
self.order.remove(page) # Remove page to update its order
|
||||
self.cache[page] = True
|
||||
self.order.append(page)
|
||||
|
||||
def display(self):
|
||||
print("Current Pages in Memory (LRU):", list(self.cache.keys()))
|
||||
|
||||
# Simulate LRU
|
||||
def lru_simulation(pages, capacity):
|
||||
lru = LRU(capacity)
|
||||
for page in pages:
|
||||
lru.refer(page)
|
||||
lru.display()
|
||||
|
||||
# Example Pages and Capacity
|
||||
pages = [7, 0, 1, 2, 0, 3, 0, 4]
|
||||
capacity = 3
|
||||
print("LRU Page Replacement Simulation:")
|
||||
lru_simulation(pages, capacity)
|
||||
@@ -1,44 +0,0 @@
|
||||
class Optimal:
|
||||
def __init__(self, capacity):
|
||||
self.capacity = capacity
|
||||
self.cache = []
|
||||
|
||||
def refer(self, page, future):
|
||||
if page not in self.cache:
|
||||
if len(self.cache) < self.capacity:
|
||||
self.cache.append(page)
|
||||
else:
|
||||
farthest_page = self.find_farthest_page(future)
|
||||
index = self.cache.index(farthest_page)
|
||||
self.cache[index] = page
|
||||
|
||||
def find_farthest_page(self, future):
|
||||
farthest = -1
|
||||
farthest_page = None
|
||||
for page in self.cache:
|
||||
if page not in future:
|
||||
return page
|
||||
try:
|
||||
index = future.index(page)
|
||||
if index > farthest:
|
||||
farthest = index
|
||||
farthest_page = page
|
||||
except ValueError:
|
||||
continue
|
||||
return farthest_page
|
||||
|
||||
def display(self):
|
||||
print("Current Pages in Memory (Optimal):", self.cache)
|
||||
|
||||
# Simulate Optimal Page Replacement
|
||||
def optimal_simulation(pages, capacity):
|
||||
optimal = Optimal(capacity)
|
||||
for i in range(len(pages)):
|
||||
optimal.refer(pages[i], pages[i + 1:])
|
||||
optimal.display()
|
||||
|
||||
# Example Pages and Capacity
|
||||
pages = [7, 0, 1, 2, 0, 3, 0, 4]
|
||||
capacity = 3
|
||||
print("\nOptimal Page Replacement Simulation:")
|
||||
optimal_simulation(pages, capacity)
|
||||
@@ -1,19 +0,0 @@
|
||||
# Python version
|
||||
|
||||
---
|
||||
|
||||
- This folder contains Python versions of all codes.
|
||||
- All codes have been tested.
|
||||
- **ROUND ROBIN DOES NOT WORK AS INTENDED.**
|
||||
|
||||
---
|
||||
|
||||
- [Assignment-A1 (Pass 1 and pass 2 assembler)](Assignment-A1%20%28Assembler%29)
|
||||
- [Assignment-A2 (Pass 1 and pass 2 macro)](Assignment-A2%20%28Macro%29) // Alternate version available in [Codes/Group A](../Group%20A/Code-A2.py) folder.
|
||||
- [Assignment-A3 (DLL)](../Group%20A/Assignment-A3) - This code is from "Codes/Group A" folder
|
||||
- [Assignment-B4 (Mutex and Semaphore)](../Group%20B/Code-B4.cpp) - This code is from "Codes/Group B" folder
|
||||
- [Assignment-B5 (CPU scheduling)](Assignment-B5%20%28CPU%20Scheduling%29)
|
||||
- [Assignment-B6 (Memory placement)](Assignment-B6%20%28Memory%20placement%29)
|
||||
- [Assignment-B7 (Page replacement)](Assignment-B7%20%28Page%20replacement%29)
|
||||
|
||||
---
|
||||
Executable
+67
@@ -0,0 +1,67 @@
|
||||
#include <iostream>
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct Process {
|
||||
int id;
|
||||
int burstTime;
|
||||
int remainingTime;
|
||||
int waitingTime;
|
||||
int turnaroundTime;
|
||||
};
|
||||
|
||||
void roundRobinScheduling(vector<Process> &processes, int quantum) {
|
||||
int n = processes.size();
|
||||
queue<int> readyQueue;
|
||||
vector<int> completionTimes(n, 0);
|
||||
|
||||
int currentTime = 0;
|
||||
|
||||
for (int i = 0; i < n; ++i) {
|
||||
readyQueue.push(i);
|
||||
processes[i].remainingTime = processes[i].burstTime;
|
||||
}
|
||||
|
||||
while (!readyQueue.empty()) {
|
||||
int currentProcessId = readyQueue.front();
|
||||
readyQueue.pop();
|
||||
|
||||
if (processes[currentProcessId].remainingTime <= quantum) {
|
||||
currentTime += processes[currentProcessId].remainingTime;
|
||||
processes[currentProcessId].remainingTime = 0;
|
||||
processes[currentProcessId].turnaroundTime = currentTime;
|
||||
processes[currentProcessId].waitingTime = processes[currentProcessId].turnaroundTime - processes[currentProcessId].burstTime;
|
||||
completionTimes[currentProcessId] = currentTime;
|
||||
} else {
|
||||
currentTime += quantum;
|
||||
processes[currentProcessId].remainingTime -= quantum;
|
||||
readyQueue.push(currentProcessId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
cout<<"Time Quantum = 4";
|
||||
cout << "Process ID\tBurst Time\tWaiting Time\tTurnaround Time\n";
|
||||
for (int i = 0; i < n; ++i) {
|
||||
cout << processes[i].id << "\t\t" << processes[i].burstTime << "\t\t" << processes[i].waitingTime
|
||||
<< "\t\t" << processes[i].turnaroundTime << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
vector<Process> processes = {
|
||||
{1, 6, 0, 0, 0},
|
||||
{2, 8, 0, 0, 0},
|
||||
{3, 7, 0, 0, 0},
|
||||
{4, 3, 0, 0, 0}
|
||||
};
|
||||
|
||||
int timeQuantum = 4;
|
||||
|
||||
roundRobinScheduling(processes, timeQuantum);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Executable
+54
@@ -0,0 +1,54 @@
|
||||
#Original Code, Engineered by Afan Shaikh.
|
||||
try:
|
||||
source= open('source.txt', 'r')
|
||||
dum = source.readline()
|
||||
print("File is read successfully.")
|
||||
source.seek(0)
|
||||
except FileNotFoundError:
|
||||
print('\n\n\nsource.txt file not found. Create it first!\n\n\n')
|
||||
except IOError:
|
||||
print('The source file has an IO error')
|
||||
|
||||
|
||||
MDT =[]
|
||||
MNT =[]
|
||||
|
||||
def macroman(line):
|
||||
name = line.split()[1] #A concise way to get the 2nd word-> name of macro. index =1. first split and then get 2nd word
|
||||
entry = []
|
||||
entry.append(line.strip()) #append the macro definition line
|
||||
while True:
|
||||
line=source.readline().upper()
|
||||
if not line:
|
||||
print('No MEND found for: ', name)
|
||||
return
|
||||
if 'MACRO' in line:
|
||||
macroman(line)
|
||||
elif 'MEND' in line:
|
||||
global MDT, MNT
|
||||
entry.append(line.strip()) #MEND line appended too
|
||||
MNT.append([len(MNT)+1, name, len(MDT)+1]) # Eg. 1 Fibo 50
|
||||
MDT = MDT + entry
|
||||
return
|
||||
else:
|
||||
entry.append(line.strip())
|
||||
|
||||
|
||||
def driver():
|
||||
global MDT, MNT
|
||||
while True:
|
||||
line = source.readline().upper()
|
||||
if not line:break
|
||||
if 'MACRO' in line:
|
||||
macroman(line)
|
||||
print('\nMNT:')
|
||||
for a in MNT:
|
||||
print(a)
|
||||
print('\n\nMDT:')
|
||||
i=0
|
||||
for a in MDT:
|
||||
i=i+1
|
||||
print (i, ' ',a)
|
||||
|
||||
driver()
|
||||
|
||||
Executable
+53
@@ -0,0 +1,53 @@
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
using namespace std;
|
||||
|
||||
struct Process {
|
||||
int id;
|
||||
int burstTime;
|
||||
int priority;
|
||||
int waitingTime;
|
||||
int turnaroundTime;
|
||||
};
|
||||
|
||||
bool comparePriority(Process a, Process b) {
|
||||
return a.priority > b.priority;
|
||||
}
|
||||
|
||||
void priorityScheduling(vector<Process> &processes) {
|
||||
int n = processes.size();
|
||||
|
||||
sort(processes.begin(), processes.end(), comparePriority);
|
||||
|
||||
processes[0].waitingTime = 0;
|
||||
processes[0].turnaroundTime = processes[0].burstTime;
|
||||
for (int i = 1; i < n; ++i) {
|
||||
processes[i].waitingTime = 0;
|
||||
for (int j = 0; j < i; ++j) {
|
||||
processes[i].waitingTime += processes[j].burstTime;
|
||||
}
|
||||
processes[i].turnaroundTime = processes[i].waitingTime + processes[i].burstTime;
|
||||
}
|
||||
|
||||
cout << "Process ID\tBurst Time\tPriority\tWaiting Time\tTurnaround Time\n";
|
||||
for (const auto &p : processes) {
|
||||
cout << p.id << "\t\t" << p.burstTime << "\t\t" << p.priority
|
||||
<< "\t\t" << p.waitingTime << "\t\t" << p.turnaroundTime << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
vector<Process> processes = {
|
||||
{1, 6, 2, 0, 0},
|
||||
{2, 8, 1, 0, 0},
|
||||
{3, 7, 3, 0, 0},
|
||||
{4, 3, 4, 0, 0}
|
||||
};
|
||||
|
||||
priorityScheduling(processes);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
macro add
|
||||
a1
|
||||
maCro sub
|
||||
s1
|
||||
s2
|
||||
s3
|
||||
mend
|
||||
a2
|
||||
mend
|
||||
These lines should not come in MNT
|
||||
help haha aha
|
||||
Reference in New Issue
Block a user