#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

const int MAX_PROCESS = 10;
const int MAX_RESOURCE = 10;

int available[MAX_RESOURCE];
int allocation[MAX_PROCESS][MAX_RESOURCE];
int max_need[MAX_PROCESS][MAX_RESOURCE];
int need[MAX_PROCESS][MAX_RESOURCE];
bool finish[MAX_PROCESS];

vector<int> safe_sequence;

void take_input(int p, int r) {
    cout << "Enter the available resources: ";
    for(int i = 0; i < r; i++) {
        cin >> available[i];
    }

    for(int i = 0; i < p; i++) {
        cout << "Enter the allocation for process " << i << ": ";
        for(int j = 0; j < r; j++) {
            cin >> allocation[i][j];
        }
    }

    for(int i = 0; i < p; i++) {
        cout << "Enter the maximum need for process " << i << ": ";
        for(int j = 0; j < r; j++) {
            cin >> max_need[i][j];
            need[i][j] = max_need[i][j] - allocation[i][j];
        }
        finish[i] = false;
    }
}

bool is_safe(int p, int r) {
    int work;
    for(int i = 0; i < r; i++) {
        work[i] = available[i];
    }

    bool finished[p];
    for(int i = 0; i < p; i++) {
        finished[i] = false;
    }

    int count = 0;
    while(count < p) {
        bool found = false;
        for(int i = 0; i < p; i++) {
            if(!finished[i]) {
                int j;
                for(j = 0; j < r; j++) {
                    if(need[i][j] > work[j]) {
                        break;
                    }
                }
                if(j == r) {
                    for(int k = 0; k < r; k++) {
                        work[k] += allocation[i][k];
                    }
                    finished[i] = true;
                    found = true;
                    safe_sequence.push_back(i);
                    count++;
                }
            }
        }
        if(!found) {
            return false;
        }
    }
    return true;
}

bool request_resources(int p, int r, int process_num, int *request) {
    for(int i = 0; i < r; i++) {
        if(request[i] > need[process_num][i] || request[i] > available[i]) {
            return false;
        }
    }
    for(int i = 0; i < r; i++) {
        available[i] -= request[i];
        allocation[process_num][i] += request[i];
        need[process_num][i] -= request[i];
    }
    if(is_safe(p, r)) {
        return true;
    }
    else {
        for(int i = 0; i < r; i++) {
            available[i] += request[i];
            allocation[process_num][i] -= request[i];
            need[process_num][i] += request[i];
        }
        return false;
    }
}

int main() {
    int p, r;
    cout << "Enter the number of processes: ";
    cin >> p;
    cout << "Enter the number of resources: ";
    cin >> r;

    take_input(p, r);

    if(is_safe(p, r)) {
        cout << "The system is in safe state."
JOIN OUR NEWSLETTER
And get notified everytime we publish a new blog post.