I have a vector of structs, with the structs looking like this:
struct myData{
int ID;
int arrivalTime;
int burstTime;
};
After populating my vector with this data:
1 5 16
4 7 12
3 12 4
2 7 8
where each row is an individual struct's ID (arbitrary, doesn't denote order of arrival), arrivalTime and burstTime, how would I use "for" or "while" loops to step through my vector's indices and calculate the data in a way that I could print something like this out?
Time 0 Processor is Idle
Time 5 Process 1 starts running
Time 21 Process 2 is running
Time 29 Process 4 is running
Time 41 Process 3 is running
The way I thought I could do it was to have an integer keep track what the current time is (the current time being the sum of the burst times of processes that have already ran) but I can't seem to figure out an algorithm that accounts for Idle time (when the processor is not doing anything and a new task hasn't arrived yet) as well as keeping track of the other numbers as well. For simplicity's sake I just decided that when two processes arrive at the same time I would process the one with the lower ID number. I know I didn't put much code here to demonstrate what I'm trying to do, but I hope I've explained it fairly clearly. I'm looking for a psuedo-code algorithm solution to this problem, but I wouldn't say no to something that has been coded (In C++?).
As an additional note, in case I wasn't able to convey how I access my data clearly, this:
cout << structVector[0].ID << "\n";
cout << structVector[0].arrivalTime << "\n";
cout << structVector[0].burstTime << "\n";
would print out
1
5
16
Any help in psuedo-code or actual code would be GREATLY appreciated!!! After reading this post over a few times I realize I've been pretty generic with the question, but I would love some help just understanding how to calculate this data.
First, sort the vector based on arrival times.
Then the following code will accomplish what you are looking for.
int i = 0, time = 0;
while (i < vec.size())
{
if (vec[i]. arrivalTime > time)
cout << "Time " << time << "process is idle";
time += vec[i].arrivalTime;
cout << "Time " << time << " Process " << vec[i].ID << " is running" << endl;
time += vec[i].burstTime;
i++;
}
Related
Good day,
I am currently in the learning process of CGAL while being relatively new to C++. For my current project I need to use Minkowski sums and then do additional operations on the boundary of it.
However, before I do these additional operations I need to get a better understanding of the output of offset_polygon_2(), the exact Minkowski offset computation.
Question 1: What is the Syntax of the output for .outer_boundary?
From what I understand so far, it outputs a list of a conic circles defined here. I would also imagine you would need some kind of arc-angle range for each of these concic circles and origin point, correct? An example of the output goes something like this:
89 {-1*x^2 + -1*y^2 + 0*xy + 1400*x + 0*y + -489975} : (705,0) --ccw--> (700,5) {0*x^2 + 0*y^2 + 0*xy + 0*x + 0*y + 0} : (700,5) --l--> (699.97,5)...
Question 2: How do you use CGAL::draw() for the above?
I have the following code, but I am unsure of what else needs to be done before it can be drawn.
Offset_polygon_with_holes_2 offset = CGAL::offset_polygon_2(P, 5, traits);
double secs = timer.time();
std::cout << "The offset polygon has " << offset.outer_boundary().size()
<< " vertices, " << offset.number_of_holes() << " holes."
<< std::endl;
std::cout << "Offset computation took " << secs << " seconds." << std::endl;
Question 3: What other operations can be done on the "offset"?
So in the example code for Minkowski sums (also see above) offset.outer_boundary() is done, is there a list of other operations that can be done? Note: I do not think "operations" is the correct term here, please correct me.
I think that is all I have for now, thanks!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
My program needs to be able to calculate the monthly phone bill and there are 3 plans: Basic where 10 hours are free and it costs 9.95, Gold where 20 hours are free and it costs 14.95, and Platinum where you have unlimited hours and it costs 19.95. When my program is given hours less than the free hours it subtracts them from the initial cost, and also it has build hours.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//Set up the variables.
string input;
int hours;
int basicHours;
int goldHours;
float extraBasic;
float basicCost;
float goldCost;
// Will ask and display the user their plan and hours.
cout << "Hello! Welcome to the Comms4You Telecom Company!" << endl;
cout << "Please provide your plan." << endl;
cin >> input;
cout << input << ", Ok now please provide the amount of hours you used." << endl;
cin >> hours;
//Calculate different equations
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
//This part is for displaying to the users plans and hours.(Also calculations)
if (input == "Platinum") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $19.95.";
}
else if (input == "Gold") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << goldCost << ".";
}
else if (input == "Basic") {
cout << "Our company thanks you for using " << hours << " hours! " << "Your total cost is $" << basicCost << ".";
}
else
return 0;
}
The problem is in these lines:
basicHours = (hours - 10);
goldHours = (20 - hours);
extraBasic = (basicHours * 2);
basicCost = (9.95 + extraBasic);
goldCost = (14.95 + goldHours);
Think about what they are doing.
basicHours = (hours - 10);
If hours was 11, then basicHours is now 11 - 10 = 1. This is good. But if hours was 9, then basicHours is now 9 - 10 = -1. This is not what you want; if I used less than my 10 free hours, then you want basicHours to be 0.
So you can write instead:
if (hours > 10) {
basicHours = hours - 10;
}
else {
basicHours = 0;
}
or equivalently:
basicHours = (hours > 10) ? hours - 10 : 0;
goldHours = (20 - hours)
This should be the exact same thing as basicHours, except with 20 instead of 10! I will let you adapt the above code.
basicCost = (9.95 + extraBasic); and goldCost = (14.95 + goldHours);
This is wrong. 9.95 is a monetary value, say in euros. extraBasic is a time, in hours. You cannot add hours with euros! If I used 12 hours with the basic plan, what is the result of 9.95€ + 2h? I do not know, it does not make sense.
If I used 12 hours with the basic plan, then I have to pay 9.95€, and I have to pay for the extra 2h. What is the cost of the extra 2h? It is 2 times the cost of an hour; in other words, it's the extra time multiplied by the hourly rate. You should have a constant variable called hourlyRate or basicHourlyRate in your program, with that value. Then you can write:
basicCost = 9.95 + extraBasic * basicHourlyRate;
goldCost = 14.95 + goldHours * goldHourlyRate;
Coding style: separate data and code
A good rule to follow is never to put data in your code. All literal values are data. The cost of the basic and gold and platinum plans are data. The hourly rate is data. The number of "free" hours for each plan is data. Define a few variables with explicit names, initialize those variables with the data at the very beginning of the code, then write the rest of the code without ever using a literal value. There are two reasons why this is important.
The code will be easier to read with variables. Explicit names in variables make the code meaningful; if you use literal values inside the code, the people reading your code don't know what those values stand for. Why do you subtract 10 from hours? We have to think about where this 10 comes from. However, if you write basicPayingHours = hours - freeBasicHours, we understand immediately. "The people reading your code" include StackOverflow members you're showing your code to, but also your schoolmates or coworkers, your teacher or boss, and most importantly, yourself when you read your code again six months from now.
When the data changes, it will be a lot easier to update your code if data is cleanly separated from code. Imagine you are working for this phone company. Next year, they update their plans and the basic plan is now 9.99 per month instead of 9.95. If this value is stored at the beginning of your code in a line basicPlanInitialCost = 9.95;, it is very easy to update it. However if there are multiple occurrences of 9.95 in your code, you will have to track them and change them all manually - this process is very prone to errors for two reasons: you might accidentally change the cost of something else that also costs 9.95; you might forget to update values that are dependent on the monthly price of the basic cost (like the yearly price of the basic cost, which is 12 * 9.95 = 119.40).
I am having trouble getting this program to output properly. It simulates a drunken sailor on a board that randomly goes one step to the left or right. At the end of the simulation, the program outputs the percentage of times he fell off the board vs not falling off. My percentage is always zero, and I can't figure out whats wrong with my code.
This function correctly outputs the "experiments" and "fallCount" variable, but always displays "fallCount / experiments" as zero.
This should read "After 2 experiments, sailor fell 1 time, fall percentage was 0.5%"
(if experiments = 2 and fallCount = 1) instead, its 0% every time.
Let me know what I am doing wrong. Thank you!
void outputExperimentStats(int experiments, int fallCount)
{
cout << "After " << experiments << " experiments, sailor fell "
<< fallCount << " time, fall percentage was " << fallCount / experiments << "%\n";
}
That is because you are using integer division. There are no decimals, so things get truncated. E.g.
1 / 2 --> 0 // integer division
This is correct, and expected behavior.
To get the behavior you want, use double or float.
1.0 / 2.0 --> 0.5 // double division
In your example, you can either change the types of your inputs to double or if you want to keep them int, you can convert them during the division
static_cast<double>(fallCount) / static_cast<double>(experiments)
I have this multimap in my code:
multimap<long, Note> noteList;
// notes are added with this method. measureNumber is minimum `1` and doesn't go very high
void Track::addNote(Note ¬e) {
long key = note.measureNumber * 1000000 + note.startTime;
this->noteList.insert(make_pair(key, note));
}
I'm encountering problems when I try to read the notes from the last measure. In this case the song has only 8 measures and it's measure number 8 that causes problems. If I go up to 16 measures it's measure 16 that causes the problem and so on.
// (when adding notes I use as key the measureNumber * 1000000. This searches for notes within the same measure)
for(noteIT = trackIT->noteList.lower_bound(this->curMsr * 1000000); noteIT->first < (this->curMsr + 1) * 1000000; noteIT++){
if(this->curMsr == 8){
cout << "_______________________________________________________" << endl;
cout << "ID:" << noteIT->first << endl;
noteIT->second.toString();
int blah = 0;
}
// code left out here that processes the notes
}
I have only added one note to the 8th measure and yet this is the result I'm getting in console:
_______________________________________________________
ID:8000001
note toString()
Duration: 8
Start Time: 1
Frequency: 880
_______________________________________________________
ID:1
note toString()
Duration: 112103488
Start Time: 44
Frequency: 0
_______________________________________________________
ID:8000001
note toString()
Duration: 8
Start Time: 1
Frequency: 880
_______________________________________________________
ID:1
note toString()
Duration: 112103488
Start Time: 44
Frequency: 0
This keeps repeating. The first result is a correct note which I've added myself but I have no idea where the note with ID: 1 is coming from.
Any ideas how to avoid this? This loop gets stuck repeating the same two results and I can't get out of it. Even if there are several notes within measure 8 (so that means several values within the multimap that start with 8xxxxxx it only repeats the first note and the non-existand one.
You aren't checking for the end of your loop correctly. Specifically there is no guarantee that noteIT does not equal trackIT->noteList.end(). Try this instead
for (noteIT = trackIT->noteList.lower_bound(this->curMsr * 1000000);
noteIT != trackIT->noteList.end() &&
noteIT->first < (this->curMsr + 1) * 1000000;
++noteIT)
{
For the look of it, it might be better to use some call to upper_bound as the limit of your loop. That would handle the end case automatically.
Just for fun I created an algorithm that computes every possible combination from a given rugby score (3, 5 or 7 points). I found two methods : The first one is brute force, 3 imbricated for loops. The other one is recursion.
Problem is some combinations appear multiple times. How can I avoid that ?
My code :
#include <iostream>
using namespace std;
void computeScore( int score, int nbTryC, int nbTryNC, int nbPenalties );
int main()
{
int score = 0;
while (true)
{
cout << "Enter score : ";
cin >> score;
cout << "---------------" << endl << "SCORE = " << score << endl
<< "---------------" << endl;
// Recursive call
computeScore(score, 0, 0, 0);
}
return 0;
}
void computeScore( int score, int nbTryC, int nbTryNC, int nbPenalties )
{
const int tryC = 7;
const int tryNC = 5;
const int penalty = 3;
if (score == 0)
{
cout << "* Tries: " << nbTryC << " | Tries NT: " << nbTryNC
<< " | Penal/Drops: " << nbPenalties << endl;
cout << "---------------" << endl;
}
else if (score < penalty)
{
// Invalid combination
}
else
{
computeScore(score - tryC, nbTryC+1, nbTryNC, nbPenalties);
computeScore(score - tryNC, nbTryC, nbTryNC+1, nbPenalties);
computeScore(score - penalty, nbTryC, nbTryNC, nbPenalties+1);
}
}
One way to think about this is to realize that any time you have a sum, you can put it into some "canonical" form by sorting all the values. For example, given
20 = 5 + 7 + 3 + 5
You could also write this as
20 = 7 + 5 + 5 + 3
This gives a few different options for how to solve your problem. First, you could always sort and record all of the sums that you make, never outputting the same sum twice. This has the problem that you're going to end up repeatedly generating the same sums multiple different times, which is extremely inefficient.
The other (and much better) way to do this is to update the recursion to work in a slightly different way. Right now, your recursion works by always adding 3, 5, and 7 at each step. This is what gets everything out of order in the first place. An alternative approach would be to think about adding in all the 7s you're going to add, then all the 5's, then all the 3's. In other words, your recursion would work something like this:
Let kValues = {7, 5, 3}
function RecursivelyMakeTarget(target, values, index) {
// Here, target is the target to make, values are the number of 7's,
// 5's, and 3's you've used, and index is the index of the number you're
// allowed to add.
// Base case: If we overshot the target, we're done.
if (target < 0) return;
// Base case: If we've used each number but didn't make it, we're done.
if (index == length(kValues)) return;
// Base case: If we made the target, we're done.
if (target == 0) print values; return;
// Otherwise, we have two options:
// 1. Add the current number into the target.
// 2. Say that we're done using the current number.
// Case one
values[index]++;
RecursivelyMakeTarget(target - kValues[index], values, index);
values[index]--;
// Case two
RecursivelyMakeTarget(target, values, index + 1);
}
function MakeTarget(target) {
RecursivelyMakeTarget(target, [0, 0, 0], 0);
}
The idea here is to add in all of the 7's you're going to use before you add in any 5's, and to add in any 5's before you add in any 3's. If you look at the shape of the recursion tree that's made this way, you will find that no two paths end up trying out the same sum, because when the path branches either a different number was added in or the recursion chose to start using the next number in the series. Consequently, each sum is generated exactly once, and no duplicates will be used.
Moreover, this above approach scales to work with any number of possible values to add, so if rugby introduces a new SUPER GOAL that's worth 15 points, you could just update the kValues array and everything would work out just fine.
Hope this helps!
Each time you find a solution you could store it in a dictionary ( a set of strings for example, with strings looking like "TC-TNT-P" )
Before printing a solution you verify it was not in the dictionary.
A nested for-loop is the natural way to do this. Using recursion is just silly (as you seem to have discovered).