Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.3 kB
1
Indexable
Never
#include <iostream>
#include <vector>
#include<climits>
#include <algorithm>

using namespace std;

struct Process {
    int pid;            
    int arrival_time;   
    int burst_time;     
    int remaining_time; 

    Process(int id, int arrival, int burst)
        : pid(id), arrival_time(arrival), burst_time(burst), remaining_time(burst) {}
};

bool compareArrivalTime(const Process& a, const Process& b) {
    return a.arrival_time < b.arrival_time;
}

int main() {
 
    int n=5;
    int ct[n],tat[n],wt[n];
    int at[5]={1,2,3,4,5};
    int bt[5]={8,4,2,1,3};

    vector<Process> processes;
    
    for (int i = 0; i < n; ++i) {
        int arrival, burst;
        arrival=at[i];
        burst=bt[i];
        processes.push_back(Process(i + 1, arrival, burst));
    }

    
    sort(processes.begin(), processes.end(), compareArrivalTime);

    int current_time = 0;
    int completed_processes = 0;

    cout << "Gantt Chart:\n";
    while (completed_processes < n) {
        int shortest_remaining_time = INT_MAX;
        int shortest_index = -1;

        for (int i = 0; i < n; ++i) {
            if (processes[i].arrival_time <= current_time && processes[i].remaining_time > 0) {
                if (processes[i].remaining_time < shortest_remaining_time) {
                    shortest_remaining_time = processes[i].remaining_time;
                    shortest_index = i;
                }
            }
        }

        if (shortest_index == -1) {
            current_time++;
        } else {
            processes[shortest_index].remaining_time--;
            cout << "P" << processes[shortest_index].pid << " ";
            current_time++;

            if (processes[shortest_index].remaining_time == 0) {
                completed_processes++;
            }
        }
    }
    cout<<endl;
    cout << "Process\tArrival Time\tBurst Time\tCompletion Time\tTurnaround Time\tWaiting Time\n";
    	cout<<endl;
    float avgtat = 0, avgwt = 0;
for (int i = 0; i < n; i++) {
        avgtat += (current_time - processes[i].arrival_time);
        avgwt += (current_time - processes[i].arrival_time - processes[i].burst_time);
    }
    avgtat /= n;
    avgwt /= n;
    cout << "Average Turnaround time " << avgtat << "\nAverage Waiting time " << avgwt << endl;

    return 0;
    cout << "\n";
    return 0;
}