-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfcfs.cpp
More file actions
79 lines (66 loc) · 2.02 KB
/
fcfs.cpp
File metadata and controls
79 lines (66 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/*
Title: First Come First Serve (FCFS) CPU Scheduling
Description: Implements FCFS scheduling using arrival and burst times with Gantt chart and time display.
Time Complexity: O(n log n) (for sorting)
Space Complexity: O(n)
*/
#include <bits/stdc++.h>
using namespace std;
struct Process {
int pid, at, bt;
};
// Sort by Arrival Time
bool compareArrival(Process &a, Process &b) {
return a.at < b.at;
}
// Print Gantt Chart
void printGanttChart(vector<int> &gantt, vector<int> &time) {
cout << "\nGantt Chart:\n";
for (int pid : gantt)
cout << "| P" << pid << " ";
cout << "|\n";
for (int i = 0; i < time.size(); i++)
cout << time[i] << " " ;
cout << "\n";
}
int main() {
int n;
cout << "Enter number of processes: ";
cin >> n;
vector<Process> p(n);
for (int i = 0; i < n; i++) {
p[i].pid = i + 1;
cout << "\nEnter details for Process " << i + 1 << "\n";
cout << "Arrival Time: ";
cin >> p[i].at;
cout << "Burst Time: ";
cin >> p[i].bt;
}
sort(p.begin(), p.end(), compareArrival);
vector<int> wt(n), tat(n), ct(n);
vector<int> gantt, time;
float totalWT = 0, totalTAT = 0;
int current = max(0, p[0].at);
time.push_back(current);
for (int i = 0; i < n; i++) {
current = max(current, p[i].at);
current += p[i].bt;
ct[i] = current;
tat[i] = ct[i] - p[i].at;
wt[i] = tat[i] - p[i].bt;
gantt.push_back(p[i].pid);
time.push_back(ct[i]);
}
cout << "\n--- First Come First Serve (FCFS) ---\n";
cout << "PID\tAT\tBT\tCT\tTAT\tWT\n";
for (int i = 0; i < n; i++) {
cout << "P" << p[i].pid << "\t" << p[i].at << "\t" << p[i].bt << "\t"<<ct[i]<<"\t"
<< tat[i] << "\t" << wt[i] << "\n";
totalWT += wt[i];
totalTAT += tat[i];
}
cout << "Average Waiting Time = " << totalWT / n << "\n";
cout << "Average Turnaround Time = " << totalTAT / n << "\n";
printGanttChart(gantt, time);
return 0;
}