Question

C++ ================================== Define a problem utilizing Queues and Priority Queues. Write the design, code and display...

C++

==================================

Define a problem utilizing Queues and Priority Queues. Write the design, code and display output.

Include source code and output. If no output explain the reason why and what you are going to do make sure it does not happen again aka learning from your mistakes.


Problem:
Design:
Code:
Output:

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Problem on Queue:

PROBLEM: LRU Cache Implementation

DESIGN: Queue is implemented using a doubly linked list. The maximum size of the queue will be equal to the total number of frames available(cache size). The most recently used pages will be near front end and the least recently pages will be near the rear end.

A Hash with page number as key and address of the corresponding queue node as value.

CODE:

#include <bits/stdc++.h>
using namespace std;

class LRUCache {
    // store keys of cache
    list<int> dq;

    // store references of key in cache
    unordered_map<int, list<int>::iterator> ma;
    int csize; // maximum capacity of cache

public:
    LRUCache(int);
    void refer(int);
    void display();
};

// Declare the size
LRUCache::LRUCache(int n)
{
    csize = n;
}

// Refers key x with in the LRU cache
void LRUCache::refer(int x)
{
    // not present in cache
    if (ma.find(x) == ma.end()) {
        // cache is full
        if (dq.size() == csize) {
            // delete least recently used element
            int last = dq.back();

            // Pops the last elmeent
            dq.pop_back();

            // Erase the last
            ma.erase(last);
        }
    }

    // present in cache
    else
        dq.erase(ma[x]);

    // update reference
    dq.push_front(x);
    ma[x] = dq.begin();
}

// Function to display contents of cache
void LRUCache::display()
{

    // Iterate in the deque and print
    // all the elements in it
    for (auto it = dq.begin(); it != dq.end();
         it++)
        cout << (*it) << " ";

    cout << endl;
}

// Driver Code
int main()
{
    LRUCache ca(4);

    ca.refer(1);
    ca.refer(2);
    ca.refer(3);
    ca.refer(1);
    ca.refer(4);
    ca.refer(5);
    ca.display();

    return 0;
}

OUTPUT: 5 4 1 3

Problem on priority queues

PROBLEM: Priority CPU Scheduling

DESIGN: Priority scheduling is one of the most common scheduling algorithms in batch systems. Each process is assigned a priority. Process with the highest priority is to be executed first and so on.
Processes with the same priority are executed on first come first served basis. Priority can be decided based on memory requirements, time requirements or any other resource requirement.

implementation:

1- First input the processes with their burst time
   and priority.
2- Sort the processes, burst time and priority
   according to the priority.
3- Now simply apply FCFS algorithm.

CODE:

#include<bits/stdc++.h>
using namespace std;

struct Process
{
    int pid; // Process ID
    int bt;   // CPU Burst time required
    int priority; // Priority of this process
};

// Function to sort the Process acc. to priority
bool comparison(Process a, Process b)
{
    return (a.priority > b.priority);
}

// Function to find the waiting time for all
// processes
void findWaitingTime(Process proc[], int n,
                     int wt[])
{
    // waiting time for first process is 0
    wt[0] = 0;

    // calculating waiting time
    for (int i = 1; i < n ; i++ )
        wt[i] = proc[i-1].bt + wt[i-1] ;
}

// Function to calculate turn around time
void findTurnAroundTime( Process proc[], int n,
                         int wt[], int tat[])
{
    // calculating turnaround time by adding
    // bt[i] + wt[i]
    for (int i = 0; i < n ; i++)
        tat[i] = proc[i].bt + wt[i];
}

//Function to calculate average time
void findavgTime(Process proc[], int n)
{
    int wt[n], tat[n], total_wt = 0, total_tat = 0;

    //Function to find waiting time of all processes
    findWaitingTime(proc, n, wt);

    //Function to find turn around time for all processes
    findTurnAroundTime(proc, n, wt, tat);

    //Display processes along with all details
    cout << "\nProcesses "<< " Burst time "
         << " Waiting time " << " Turn around time\n";

    // Calculate total waiting time and total turn
    // around time
    for (int i=0; i<n; i++)
    {
        total_wt = total_wt + wt[i];
        total_tat = total_tat + tat[i];
        cout << "   " << proc[i].pid << "\t\t"
             << proc[i].bt << "\t    " << wt[i]
             << "\t\t " << tat[i] <<endl;
    }

    cout << "\nAverage waiting time = "
         << (float)total_wt / (float)n;
    cout << "\nAverage turn around time = "
         << (float)total_tat / (float)n;
}

void priorityScheduling(Process proc[], int n)
{
    // Sort processes by priority
    sort(proc, proc + n, comparison);

    cout<< "Order in which processes gets executed \n";
    for (int i = 0 ; i < n; i++)
        cout << proc[i].pid <<" " ;

    findavgTime(proc, n);
}

// Driver code
int main()
{
    Process proc[] = {{1, 10, 2}, {2, 5, 0}, {3, 8, 1}};
    int n = sizeof proc / sizeof proc[0];
    priorityScheduling(proc, n);
    return 0;
}

OUTPUT:

Order in which processes gets executed
1 3 2
Processes Burst time Waiting time Turn around time
1        10     0         10
3        8     10         18
2        5     18         23

Average waiting time = 9.33333
Average turn around time = 17

Add a comment
Know the answer?
Add Answer to:
C++ ================================== Define a problem utilizing Queues and Priority Queues. Write the design, code and display...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Define a problem with user input, user output and mathematical computation. Include source code and output....

    Define a problem with user input, user output and mathematical computation. Include source code and output. If no output explain the reason why and what you are going to do make sure it does not happen again aka learning from your mistakes. (JAVA) Define a problem with user input, user output and mathematical computation Include source code and output. If no output explain the reason why and what you are going to do make sure it does not happen again...

  • Define a problem utilizing an efficient sorting algorithm please write code in c++ oop thnx?

    Define a problem utilizing an efficient sorting algorithm please write code in c++ oop thnx?

  • A priority queue is a collection of items each having a priority. A priority queue supports three...

    A priority queue is a collection of items each having a priority. A priority queue supports three fundamental operations. You can ask a priority queue whether it is empty. You can insert an item into the priority queue with a given priority. You can remove the item from the priority queue that has the smallest priority. For example, suppose that you start with an empty priority queue and imagine performing the following steps. Insert item "one" with priority 10. Insert...

  • Problem: Design and write a C language program that can be used to calculate Voltage, Current...

    Problem: Design and write a C language program that can be used to calculate Voltage, Current and Total Resistance for a Series or Parallel or a Series Parallel circuit. The program should display the main menu that contains the three types of circuit calculations that are available and then the user will be prompted to select a circuit first. After the circuit has been selected the program should then display another menu (i.e., a submenu) requesting the necessary data for...

  • Project 1, Program Design 1. Write a C program replace.c that asks the user to enter...

    Project 1, Program Design 1. Write a C program replace.c that asks the user to enter a three-digit integer and then replace each digit by the sum of that digit plus 6 modulus 10. If the integer entered is less than 100 or greater than 999, output an error message and abort the program. A sample input/output: Enter a three-digit number: 928 Output: 584 2. Write a C program convert.c that displays menus for converting length and calculates the result....

  • C# Code: Write the code that simulates the gambling game of craps. To play the game,...

    C# Code: Write the code that simulates the gambling game of craps. To play the game, a player rolls a pair of dice (2 die). After the dice come to rest, the sum of the faces of the 2 die is calculated. If the sum is 7 or 11 on the first throw, the player wins and the game is over. If the sum is 2, 3, or 12 on the first throw, the player loses and the game is...

  • I need this in Net beans and not Python. Part 1 - Pseudo-code Design and write...

    I need this in Net beans and not Python. Part 1 - Pseudo-code Design and write the pseudo-code for the following Problem Statement. Problem Statement A company gives its employees an that will provide one of 3 results based on the following ranges of scores: Score Message on Report 90-100 Special Commendation 70-89 Pass Below 70 Fail Design a single If-Then-Else structure using pseudo-code which displays one of these messages based a score input by a user. Be sure your...

  • **WRITE IN C# INTERMEDIATE LEVEL CODE A 2ND SEMESTER STUDENT COULD UNDERSTAND WELL** Problem Statement: Write...

    **WRITE IN C# INTERMEDIATE LEVEL CODE A 2ND SEMESTER STUDENT COULD UNDERSTAND WELL** Problem Statement: Write an abstract class called Vacation includes a budget and a destination. It has an abstract method returning by how much the vacation is over or under budget. This class has two non-abstract subclasses: All-Inclusive Vacation brand (such as ClubMed, Delta Vacations, etc) a rating (you can use # of stars) price Piecemeal Vacation set of items (hotel, meal, airfare, etc) set of corresponding costs...

  • guys can you please help me to to write a pseudo code for this program and...

    guys can you please help me to to write a pseudo code for this program and write the code of the program in visual studio in.cpp. compile the program and run and take screenshot of the output and upload it. please help is really appreciated. UTF-8"CPP Instruction SU2019 LA X 119SU-COSC-1436- C Get Homework Help With Che X Facebook -1.amazonaws.com/blackboard.learn.xythos.prod/584b1d8497c84/98796290? response-content-dis 100% School of Engineering and Technology COSC1436-LAB1 Note: in the instruction of the lab change "yourLastName" to your last...

  • Can you please write the two C++ modules below is a step by step instuctions to...

    Can you please write the two C++ modules below is a step by step instuctions to follow that will make it very easy thanks. Create a module called pqueue.cpp that implements priority queues, with a header file calledpqueue.hthat describes what pqueue.cpp exports. The interface includes the following, and nothing else. Types ItemType and PriorityType are discussed below under the refinement plan. A type, PriorityQueue. Creating a PriorityQueue object with line PriorityQueue q; makes q be an initially empty priority queue....

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT