SPOS - Shortest Remaining Time First [SRTF] Program
Shortest Remaining Time First Program
Code :
import java.util.Scanner;
public class SRTFScheduling {
public static boolean allZeros(int[][] processes) {
for (int[] data: processes) {
if (data[2] != 0) {
return false;
}
}
return true;
}
public static int findShortestProcessIndex(int time, int[][] processes) {
int lowest = Integer.MAX_VALUE;
int lowestIdx = -1;
for (int i = 0; i < processes.length; i++) {
if (processes[i][1] > time || processes[i][2] == 0) {
continue;
}
if (processes[i][2] < lowest) {
lowest = processes[i][2];
lowestIdx = i;
}
}
return lowestIdx;
}
public static float calcAvg(int[] arr) {
int sum = 0;
for (int j : arr) {
sum += j;
}
return (float) sum/arr.length;
}
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.print("Enter total number of processes: ");
int totalNumProcesses = myScanner.nextInt();
int[][] processes = new int[totalNumProcesses][3];
int[] burstTimesCopy = new int[totalNumProcesses];
for (int i = 0; i < totalNumProcesses; i++) {
System.out.print("Enter Process id: ");
processes[i][0] = myScanner.nextInt();
System.out.print("Enter Arrival Time: ");
processes[i][1] = myScanner.nextInt();
System.out.print("Enter Burst Time: ");
processes[i][2] = myScanner.nextInt();
burstTimesCopy[i] = processes[i][2];
}
int[] waitingTimes = new int[totalNumProcesses];
int[] turnAroundTimes = new int[totalNumProcesses];
int time = 0;
boolean isDone;
while(true) {
isDone = allZeros(processes);
if (isDone) {
break;
}
int spIdx = findShortestProcessIndex(time, processes);
if (spIdx == -1) {
time++;
continue;
}
processes[spIdx][2] -= 1;
for (int i = 0; i < processes.length; i++) {
if (i != spIdx && processes[i][2] != 0) {
waitingTimes[i]++;
}
}
time++;
}
for (int i = 0; i < processes.length; i++) {
waitingTimes[i] -= processes[i][1];
turnAroundTimes[i] = waitingTimes[i] + burstTimesCopy[i];
}
float avgWaitingTime = calcAvg(waitingTimes);
float avgTurnAroundTime = calcAvg(turnAroundTimes);
System.out.format("%4s%4s%4s%4s%4s\n", "pid", "at", "bt", "wt", "tat");
for (int i = 0; i < totalNumProcesses; i++) {
System.out.format("%4d%4d%4d%4d%4d\n", processes[i][0], processes[i][1],
burstTimesCopy[i], waitingTimes[i], turnAroundTimes[i]);
}
System.out.println("The average waiting time is: " + avgWaitingTime);
System.out.println("The average turnaround time is: " + avgTurnAroundTime);
}
}
Post a Comment