Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
2.6 kB
2
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=6;
    int ct[n],tat[n],wt[n];
    int at[6]={0,1,2,3,4,5};
    int bt[6]={8,4,2,1,3,2};
    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) {
                ct[shortest_index]=current_time;
                completed_processes++;
            }
        }
    }
    cout<<"\n"<<endl;
    cout << "Process\t  Arrival Time\tBurst Time\tCompletion Time\t  Turnaround Time\t Waiting Time\n";
    	cout<<endl;
    float avgtat = 0, avgwt = 0;
for (int i = 0; i < n; i++) {
        //ct[i]=current_time-processes[i].arrival_time;
        tat[i]=ct[i]-processes[i].arrival_time;
        wt[i]=tat[i] - processes[i].burst_time;
        avgtat += tat[i];
        avgwt += wt[i];
    }
    avgtat /= n;
    avgwt /= n;
    for(int i=0;i<n;i++)
    {
        cout<<i+1<<"\t   "<<at[i]<<"\t\t "<<bt[i]<<"\t\t "<<ct[i]<<"\t\t   "<<tat[i]<<"\t\t\t   "<<wt[i]<<endl;
    }
    cout << "Average Turnaround time " << avgtat << "\nAverage Waiting time " << avgwt << endl;

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