Added all codes.
This commit is contained in:
parent
5197bcdb76
commit
c45d47e193
109
Codes/Group A/Assignment-A1/Code-A1.py
Executable file
109
Codes/Group A/Assignment-A1/Code-A1.py
Executable file
@ -0,0 +1,109 @@
|
|||||||
|
# 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()
|
4
Codes/Group A/Assignment-A1/source.txt
Executable file
4
Codes/Group A/Assignment-A1/source.txt
Executable file
@ -0,0 +1,4 @@
|
|||||||
|
Start 100
|
||||||
|
Label MOVER AREG, =5
|
||||||
|
add areg, =999
|
||||||
|
sub breg, x
|
35
Codes/Group A/Assignment-A3/A3.c
Normal file
35
Codes/Group A/Assignment-A3/A3.c
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
#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
|
||||||
|
}
|
||||||
|
|
47
Codes/Group A/Assignment-A3/A3.h
Normal file
47
Codes/Group A/Assignment-A3/A3.h
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
// 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
|
67
Codes/Group A/Assignment-A3/A3.java
Normal file
67
Codes/Group A/Assignment-A3/A3.java
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
// 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
39
Codes/Group A/Assignment-A3/EXPLANATION.md
Normal file
39
Codes/Group A/Assignment-A3/EXPLANATION.md
Normal file
@ -0,0 +1,39 @@
|
|||||||
|
# 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
|
||||||
|
|
||||||
|
---
|
69
Codes/Group A/Assignment-A3/README.md
Normal file
69
Codes/Group A/Assignment-A3/README.md
Normal file
@ -0,0 +1,69 @@
|
|||||||
|
## 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
|
||||||
|
```
|
100
Codes/Group A/Code-A2.py
Normal file
100
Codes/Group A/Code-A2.py
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
# 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
|
80
Codes/Group B/Assignment-B5/FCFS (Non-Preemptive).cpp
Normal file
80
Codes/Group B/Assignment-B5/FCFS (Non-Preemptive).cpp
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
#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;
|
||||||
|
}
|
||||||
|
|
100
Codes/Group B/Assignment-B5/Priority (Non-Preemptive).cpp
Normal file
100
Codes/Group B/Assignment-B5/Priority (Non-Preemptive).cpp
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
#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;
|
||||||
|
}
|
110
Codes/Group B/Assignment-B5/Round Robin (Preemptive).cpp
Normal file
110
Codes/Group B/Assignment-B5/Round Robin (Preemptive).cpp
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
#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;
|
||||||
|
}
|
82
Codes/Group B/Assignment-B5/SJF (Preemptive).cpp
Normal file
82
Codes/Group B/Assignment-B5/SJF (Preemptive).cpp
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
#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;
|
||||||
|
}
|
70
Codes/Group B/Code-B4.cpp
Normal file
70
Codes/Group B/Code-B4.cpp
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
// 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;
|
||||||
|
}
|
98
Codes/Group B/Code-B6.cpp
Normal file
98
Codes/Group B/Code-B6.cpp
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
#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;
|
||||||
|
}
|
135
Codes/Group B/Code-B7.cpp
Normal file
135
Codes/Group B/Code-B7.cpp
Normal file
@ -0,0 +1,135 @@
|
|||||||
|
// 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
|
109
Codes/Python version/Assignment-A1 (Assembler)/Code-A1.py
Normal file
109
Codes/Python version/Assignment-A1 (Assembler)/Code-A1.py
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
# 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()
|
@ -0,0 +1,8 @@
|
|||||||
|
COPY START 1000
|
||||||
|
FIRST LOAD ALPHA
|
||||||
|
ADD BETA
|
||||||
|
STORE GAMMA
|
||||||
|
ALPHA WORD 5
|
||||||
|
BETA RESW 1
|
||||||
|
GAMMA RESB 1
|
||||||
|
END FIRST
|
109
Codes/Python version/Assignment-A2 (Macro)/Code-A2.py
Normal file
109
Codes/Python version/Assignment-A2 (Macro)/Code-A2.py
Normal file
@ -0,0 +1,109 @@
|
|||||||
|
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()
|
13
Codes/Python version/Assignment-A2 (Macro)/source1.txt
Normal file
13
Codes/Python version/Assignment-A2 (Macro)/source1.txt
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
MACRO FIBO
|
||||||
|
MOVE A, =5
|
||||||
|
ADD A, B
|
||||||
|
MEND
|
||||||
|
|
||||||
|
MACRO SUM
|
||||||
|
ADD A, B
|
||||||
|
MOVE C, =100
|
||||||
|
MEND
|
||||||
|
|
||||||
|
START:
|
||||||
|
FIBO
|
||||||
|
SUM
|
23
Codes/Python version/Assignment-B5 (CPU Scheduling)/FCFS.py
Normal file
23
Codes/Python version/Assignment-B5 (CPU Scheduling)/FCFS.py
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
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))
|
@ -0,0 +1,23 @@
|
|||||||
|
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))
|
@ -0,0 +1,36 @@
|
|||||||
|
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)
|
48
Codes/Python version/Assignment-B5 (CPU Scheduling)/SJF.py
Normal file
48
Codes/Python version/Assignment-B5 (CPU Scheduling)/SJF.py
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
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))
|
@ -0,0 +1,28 @@
|
|||||||
|
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)
|
@ -0,0 +1,22 @@
|
|||||||
|
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)
|
@ -0,0 +1,25 @@
|
|||||||
|
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)
|
@ -0,0 +1,28 @@
|
|||||||
|
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)
|
31
Codes/Python version/Assignment-B7 (Page replacement)/LRU.py
Normal file
31
Codes/Python version/Assignment-B7 (Page replacement)/LRU.py
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
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)
|
@ -0,0 +1,44 @@
|
|||||||
|
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)
|
19
Codes/Python version/README.md
Normal file
19
Codes/Python version/README.md
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
# 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)
|
||||||
|
|
||||||
|
---
|
21
README.md
21
README.md
@ -9,6 +9,27 @@ This repository serves as a comprehensive resource for the Systems Programming a
|
|||||||
|
|
||||||
## Index
|
## Index
|
||||||
|
|
||||||
|
### Codes
|
||||||
|
|
||||||
|
> Checkout [python version](Codes/Python%20version) of all the codes.
|
||||||
|
|
||||||
|
##### Group A
|
||||||
|
1. [Code-A1 - Pass 1](Codes/Group%20A/Assignment-A1)
|
||||||
|
- [Code](Codes/Group%20A/Assignment-A1/Code-A1.py)
|
||||||
|
- [Source file](Codes/Group%20A/Assignment-A1/source.txt)
|
||||||
|
2. [Code-A2 - Pass 1 and Pass 2 of 2-Pass Macroprocessor](Codes/Group%20A/Code-A2.py)
|
||||||
|
3. [Code-A3 - DLL](Codes/Group%20A/Assignment-A3/)
|
||||||
|
|
||||||
|
##### Group B
|
||||||
|
4. [Code-B4 - Mutex and Semaphore](Codes/Group%20B/Code-B4.cpp)
|
||||||
|
5. [CPU Scheduling Algorithms: FCFS, SJF (Preemptive), Priority (Non-Preemptive) and Round Robin (Preemptive)](Codes/Group%20B/Assignment-B5)
|
||||||
|
- [FCFS (Non-Preemptive)](Codes/Group%20B/Assignment-B5/FCFS%20%28Non-Preemptive%29.cpp)
|
||||||
|
- [SJF (Preemptive)](Codes/Group%20B/Assignment-B5/SJF%20%28Preemptive%29.cpp)
|
||||||
|
- [Priorty (Non-Preemptive)](Codes/Group%20B/Assignment-B5/Priority%20%28Non-Preemptive%29.cpp)
|
||||||
|
- [Round Robin (Preemptive)](Codes/Group%20B/Assignment-B5/Round%20Robin%20%28Preemptive%29.cpp)
|
||||||
|
6. [Code-B6 - Memory Placement Strategies - Best Fit, First Fit, Next Fit and Worst Fit](Codes/Group%20B/Code-B6.cpp)
|
||||||
|
7. [Code-B7 - Page Replacement Algorithms - LRU(Least Recently Used), Optimal](Codes/Group%20B/Code-B7.cpp)
|
||||||
|
|
||||||
### Notes
|
### Notes
|
||||||
|
|
||||||
1. [Unit 1 - Introduction](Notes/Unit%201%20-%20Introduction)
|
1. [Unit 1 - Introduction](Notes/Unit%201%20-%20Introduction)
|
||||||
|
Loading…
Reference in New Issue
Block a user