fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. class Process {
  5. public:
  6. int id, at, bt, st, ft, wt, tat;
  7. Process(int id, int at, int bt) : id(id), at(at), bt(bt) {}
  8. Process() {}
  9.  
  10. void calculateTimes(int current_time) {
  11. st = max(current_time, at);
  12. ft = st + bt;
  13. wt = st - at;
  14. tat = wt + bt;
  15. }
  16. };
  17.  
  18. bool compareArrivalTime(const Process& a, const Process& b) {
  19. return a.at < b.at;
  20. }
  21.  
  22. int main() {
  23. int n;
  24. cout << "Enter the number of processes: ";
  25. cin >> n;
  26.  
  27. vector<Process> processes;
  28. for (int i = 0; i < n; ++i) {
  29. int bt, at;
  30. cout << "Enter the burst time of P" << i + 1 << ": ";
  31. cin >> bt;
  32. cout << "Enter the arrival time of P" << i + 1 << ": ";
  33. cin >> at;
  34. processes.push_back(Process(i + 1, at, bt));
  35. }
  36.  
  37. sort(processes.begin(), processes.end(), compareArrivalTime);
  38.  
  39. int current_time = 0;
  40. float total_wt = 0, total_tat = 0;
  41.  
  42. cout << "Gantt Chart\n";
  43. for (int i = 0; i < n; ++i) {
  44. cout << current_time << " P" << processes[i].id << " ";
  45. processes[i].calculateTimes(current_time);
  46. current_time = processes[i].ft;
  47. total_wt += processes[i].wt;
  48. total_tat += processes[i].tat;
  49. }
  50. cout << endl;
  51.  
  52. cout << "Process: Start time: Waiting time: Turnaround time:\n";
  53. for (int i = 0; i < n; ++i) {
  54. cout << "P" << processes[i].id << "\t" << processes[i].st << "\t" << processes[i].wt << "\t" << processes[i].tat << endl;
  55. }
  56.  
  57. cout << "Average waiting time: " << total_wt / n << endl;
  58. cout << "Average turnaround time: " << total_tat / n << endl;
  59.  
  60. return 0;
  61. }
  62.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
Enter the number of processes: Gantt Chart

Process: Start time: Waiting time: Turnaround time:
Average waiting time: -nan
Average turnaround time: -nan