-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpriority preemptive.cpp
More file actions
86 lines (59 loc) · 1.78 KB
/
Copy pathpriority preemptive.cpp
File metadata and controls
86 lines (59 loc) · 1.78 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
80
81
82
83
84
85
86
#include<bits/stdc++.h>
using namespace std;
struct process{
string name;
int at, bt,remaining_bt, priority, ct, tat, wt;
};
vector<process> pro = {
{"P1", 0, 5, 5, 2, 0, 0, 0},
{"P2", 1, 3, 3, 1, 0, 0, 0},
{"P3", 2, 8, 8, 4, 0, 0, 0},
{"P4", 3, 6, 6, 3, 0, 0, 0}
};
bool compareByAT(const process &p1, const process &p2){
return p1.at < p2.at; // sort ascending order
}
void show(){
cout<<setw(10)<<"name"<<setw(10)<<"at"<<setw(10)<<"bt"<<setw(10)<<"ct"<<setw(10)<<"tat"<<setw(10)<<"wt"<<endl;
for(auto &p:pro){
cout<<setw(10)<<p.name<<setw(10)<<p.at<<setw(10)<<p.bt<<setw(10)<<p.ct<<setw(10)<<p.tat<<setw(10)<<p.wt<<endl;
}
}
// logical section
void solve(){
// sort processes by at
sort(pro.begin(), pro.end(), compareByAT);
int n = pro.size();
vector<bool> visited(n, 0);
int completed = 0;
int current_time = 0;
while(completed<n){
int min_prio = DBL_MAX;
int indx = -1;
for(int i = 0; i<n; i++){
if(visited[i] == 0 && pro[i].at<=current_time && pro[i].priority < min_prio){
min_prio = pro[i].priority;
indx = i;
}
}
if(indx == -1){
current_time++;
}
else{
pro[indx].remaining_bt--;
current_time++;
if(pro[indx].remaining_bt == 0){
visited[indx] = 1;
completed++;
pro[indx].ct = current_time;
pro[indx].tat = pro[indx].ct - pro[indx].at;
pro[indx].wt = pro[indx].tat - pro[indx].bt;
}
}
}
}
int main()
{
solve();
show();
}