Assume we have been given detail of an object number, name, manufacturing date, price,
weight and there are many objects.
I have to implement a search operation which is able to search the items on the basis
of multiple conditions, for example, search the item whose manufacturing
date is before 11 2020 and price < 400(compare only price and date) or we have to compare(only price and weight) price is > 300 and weight > 30 .
If no item is found suitable, the result of the search should inform about it and if
multiple items follow the condition, they must be displayed in an ordered
way decided by the programmer (clearly mention the ordering criterion).
I tried using the structure of the array but I am stuck in performing any two searches out of six.
For searching the items:
Firstly, declare a counter variable:
int counter = 0;
for (int i = 0; i < TOTAL_ITEMS; i++) {
if (itemPrice[i] < 400 || itemPrice[i] > 300 && itemWeight[i] > 30 && manfDate[i] < 112020) {
// cout for itemsPrice[i], itemWeight[i] and manfDate[i]
counter++;
}
}
if (counter == 0) {
std::cout << "No Items Found." << std::endl;
}
Suppose there are 10 items given and their:
Price is lesser than 400 and greater than 300
Weight's more than 30 KG/LB
Manufacture date's within 11200
It'll only show the data which are TRUE conditioned. Also notice that the counter variable is only used for verifying if the value isn't zero (no items found condition).
Related
Hello and thanks for helping!
So we've got a list of fireworks containing 1) Number in stock 2) Number of fireworks in this package 3) Diameter which equals the noise and
4) The price.
This is the list:
25 17 10 21
10 15 10 18
5 16 10 19
10 15 12 20
15 9 11 12
10 7 28 23
8 7 16 11
10 6 16 10
25 10 18 25
25 12 18 27
10 5 40 35
60 40 5 27
5 25 30 90
50 1 60 8
Our task is to create a shopping list and buy fireworks so we get the highest possible noise. We've got a knapsack capacity of 1000€. We're also supposed to solve this without using tables (so with dynamic programming instead).
I only use one class called Package which contains the four constraints as shown above.
At first I thought it would make sense to try to write an algorithm for a normal knapsack, so just with the price and the diameter (=weight). I tested it with a different list and it worked perfectly fine. I just iterated through all packages and then again used a nested for loop to find the best constellation (exhaustive search). My next idea was to merge the number of fireworks per package with the diameter, because fireworks can only be bought in a full package.
The only thing left which I still haven't found out is what to do with the amount of packages in stock. Like, with my current algorithm it just buys all packages of a firework until the knapsack is full. But obviously that won't be correct.
void knapsack(vector<Package*> stock){
vector<int> indices, tmp_indices;
int noise,tmp_noise= 0;
int price;
for (unsigned int i = 0; i < stock.size(); i++) {
price = stock[i]->price;
noise = stock[i]->diameter*stock[i]->number_fireworks;
indices.push_back(i);
for (unsigned int j = 0; j < stock.size(); j++) {
if (i != j) {
if (price+stock[j]->price<= BUDGET) {
price+=stock[j]->price;
noise+=stock[j]->diameter*stock[j]->number_fireworks;
indices.push_back(j);
}
}
}
// After second loop we have a new possible constellation
// Check if the previous constellation had a lower value and if so, set it to the current one
if (noise > tmp_noise) {
tmp_noise = noise;
tmp_indices.clear();
// tmp save
for (auto &index : indices) {
tmp_indices.push_back(index);
}
}
price= 0;
noise = 0;
indices.clear();
}
// Best constellation found, Print the shopping list
cout << "\Stock.\tNum\Diameter.\Price\n" << endl;
for(unsigned int i = 0; i < tmp_indices.size(); i++) {
cout << stock[tmp_indices[i]]->stock<< "\t";
cout << stock[tmp_indices[i]]->number_fireworks<< "\t";
cout << stock[tmp_indices[i]]->diameter<< "\t";
cout << stock[tmp_indices[i]]->price<< "\t\n";
}
}
We've been told that we should be able to spend exactly 1000€ to get the correct constellation of fireworks. My idea was to add another for loop to iterate through the amount of available packages, but that didn't really work...
This was our first lesson and I'm a bit desperate, because we have only learned how to solve a knapsack problem with 2 constraints and by using a table R.
Edit: Since one user insisted to get a specific question, here it is: Is the idea of using another loop to include the third constraint correct or is there a better/easier way of doing it? Or is it possible that I need a completely different approach for a knapsack with 3 instead of 2 constraints?
Thanks for help in advance
I'm trying to create a program for an assignment that computes the rate for a long distance call, that takes in the starting time and length of call and outputs the gross cost and net cost.
There are several parameters involved, which i've implemented in conditional statements,
Any call started at or after 6:00 pm (1800) but before 8:00 am (800) is discounted 50%.
All calls are subject to a 4% federal tax.
The regular rate is $0.35 per minute.
Any call longer than 60 minutes receives a 16% discount on its cost (after any other discount is subtracted but before tax is added).
However, the first conditionals code is never executed and I've tried several different operands and still have not figured it out.
#import <iostream>
using namespace std;
int main() {
//declare variables
int startTime;
int callLength;
double grossCost = 0;
double netCost;
const double callRate = 0.35;
const double fedTax = 0.04;
const double discount1 = 0.50;
const double discount2 = 0.16;
//begin user prompt
cout << "Enter start time: " << endl;
cin >> startTime;
cout << "Enter length of call in minutes: " << endl;
cin >> callLength;
//define our grossCost
grossCost = (callLength * callRate);
//lez do some conditionals
if ((startTime >= 1800) && (startTime <= 800)){
netCost = grossCost - (grossCost * discount1);
netCost *= fedTax;
}
else if (callLength > 60){
netCost = grossCost - (grossCost * discount2);
netCost *= fedTax;
}
else{
netCost = (grossCost * fedTax);
}
//print out our final costs
cout << "gross cost : " << "$" << grossCost << endl;
cout << "net cost: " << "$" << netCost << endl;
return 0;
}
So, when trying an input of:
Enter start time: 2322
Enter length of call in minutes: 67
gross cost : $23.45
net cost: $0.78792
The netcost is not being evaluated correctly, as it is skipping the first conditional, even though the values of startTime meet the parameters.
The output should be:
Enter start time: 2322
Enter length of call in minutes: 67
gross cost: $23.45
net cost: $10.24
I'm not looking for someone to do my homework, just some pointers to lead me in the right direction, i've gone over the conditional several times and I'm still confused as to why it's not evaluating. Any help is appreciated, thanks.
You have a logic error here: a number can not be greater or equal than 1800 and less or equal than 800 at the same time. Revise the first conditional. I would break it in two parts
if((time >= 1800 & <=2400) || (time >= 0 && time <= 800)).
The actual logical mistake here is that calls after 6PM and before 8AM would exist in different days! So we do need two conditions that check on the days' boundaries as well, combined.
Edit per comment by #Reto Koradi:
The outcome won't change if we omit the boundary checks. As mentioned above, the gist of the change is to highlight the mutual exclusiveness of th two conditions, which is achieved by swapping the && out with an ||:
if (time >= 1800 || time <= 800)
The explanation why it's not working is fairly obvious, and already covered in other answers. This expression can never be true because no number is both greater than 1800 and also less than 800.
if ((startTime >= 1800) && (startTime <= 800)){
The && operator tests for both conditions to be true.
The more interesting part is why people make this mistake. And you're neither the first nor the last person to fall into this trap when starting out with logical expressions.
I believe the reason is that in natural language, we use the word "and" in ways that are very different from the logical operator. When you say "before 8 am and after 6 pm", the "and" corresponds much more to the "union" set operation. You're basically defining a set that contains "all times before 8 am" and "all times after 6 pm", which is a set union.
The logical operator that matches the "union" set operation is the logical "or". Any element that is in at least one of the input sets is part of the union. So for the union of two sets, the union is the set with elements that are in the first set or the second set.
With that understood, the correct condition is:
if ((startTime >= 1800) || (startTime <= 800)){
where || is the logical "or" operator.
Logical operations working differently from the way they are used in everyday language is not unusual at all. So you always need to be careful when translating language to logical expressions. Another popular example is that "or" in natural language mostly corresponds to an exclusive or, while the "or" operator is inclusive. So if somebody tells you that "you can take it or leave it", it means that you have to decide, while the standard logical "or" operator would actually allow you to do both.
The problem is
if ((startTime >= 1800) && (startTime <= 800)){
The two conditions are mutually exclusive. There is no number greater than 1800 and at the same time smaller than 800. You might want to fix the comparison condition like this (improved for future readers thanks to iksemyonov's comments. Please refer to his answer to this same question)
if ((startTime >= 1800) || (startTime <= 800)){
How can x > 1800 and x < 800 ever be true at the same time?. If the first is true, the statement will always be false.
C++ question- "Write a program that will calculate total savings by a student with his/her parents’ contribution. The student’s parents have agreed to add to the student’s savings based the percentage the student saved using the schedule given below" This is the if/else if I used to find out the parents contribution. I now have to make this program again except with a switch statement. I don't know exactly how to do that. The user inputs total earnings, and amount he decided to put away. (My course just started so I have to use very simple processes to do this thank you) Here's the first version:
percent_saved = money_saved / money_earned; // calculates the percent of how much was saved
if (percent_saved <.05) // this if/else if statement assigns the parents percentage of contribution to their students saving
{
parents = .01;
}
else if (percent_saved >= .05 && percent_saved < .1)
{
parents = .025;
}
else if (percent_saved >= .1 && percent_saved < .15)
{
parents = .08;
}
else if (percent_saved >= .15 && percent_saved < .25)
{
parents = .125;
}
else if (percent_saved >= .25 && percent_saved < .35)
{
parents = .15;
}
else
{
parents = .2;
}
parentsmoney = parents*money_earned; // using the correct percentage, this creates the amount of money parents will contribute
total_savings = parentsmoney + money_saved; // this adds together the parent's contribution and the student's savings
This can't (shouldn't) be done in this case: switch is only useful for discrete integer values. It is not useful for non-trivial ranges and cannot be used directly with floats.
Anyway, about half the conditionals can be removed from the if-expressions if the ordering reversed such that the tests are inchworm'ed through..
if (percent_saved >= .35) {
parents = .2;
} else if (percent_saved >= .25) {
parents = .15;
} // etc.
Now, if the requirement is to "use a switch statement" (silly homework problems), then consider first normalizing the floating value into "buckets" such that 0.05 => 1, 0.1 => 2, 0.15 => 3, etc. The resulting integer can then be checked in a relevant case (with some cases being fall-throughs), as shown in the linked question..
int bucket = rint(percent_saved / 0.05);
I've created a greedy algorithm to solve a problem (homework assignment) and since I'm learning c++ I would like to achieve the same thing but using sets.
Basically we submit the homework to an online platform, this platform as some test cases that we don't know of, and we get a score based on that. If we pass all test cases we have 100%;
The problem is like this.
We have an actor that wants to schedule appointments with the fans that answered an online questionnaire about him. Now he wants to choose the fan's that maximizes the sum of points in the questionnaire and respecting the fan's availability. He can see only one fan a day.
We have an input like this:
6
1 1 5
2 2 4
3 1 2
4 3 1
5 1 6
6 2 2
Where the first line is the number of fans and following, in each line, we have the fan id, the fan available days and the fan points achieved in the online questionnaire. I must print the ids of the fans that the actor will see and the sum of combined points of the fans. So for the above input I have the following output:
2
4
5
11
Note that if two fans have the same points, the fan prefered should be the one with the lower ID.
I've started by sorting the fans by the points of the questionnaire (decreasing order) and then by the lower id.
When reading the input, I'm adding the number of days to a set.
My idea was like this:
When iterating over the data, I check if the fan in study days available is in the set. If it is, add this fan and remove the days from the set. If the fan days is not in the set, then get the upper_bound and decrease the iterator to set the fan on the first day lower that the initial day. The algorithm stops wen the set is empty or I iterate all over the fans.
Here is my greedy function:
void greedy() {
fan_id.insert(questionnaire_result[0][0]);
days_available.erase(questionnaire_result[0][1]);
total_questionaire_sum += questionnaire_result[0][2];
int i;
for (i = 1; i < number_of_fans; i++) {
if (days_available.empty()) {
break;
} else if (days_available.count(questionnaire_result[i][1])) {
fan_id.insert(questionnaire_result[i][0]);
days_available.erase(questionnaire_result[i][1]);
total_questionaire_sum += questionnaire_result[i][2];
} else {
it = days_available.upper_bound(questionnaire_result[i][1]);
if (it == days_available.begin()) {
if (*it < questionnaire_result[i][1]) {
fan_id.insert(questionnaire_result[i][0]);
days_available.erase(*it);
total_questionaire_sum += questionnaire_result[i][2];
}
} else if (it == days_available.end()) {
it--;
if (*it < questionnaire_result[i][1]) {
fan_id.insert(questionnaire_result[i][0]);
days_available.erase(*it);
total_questionaire_sum += questionnaire_result[i][2];
}
} else {
it--;
if (*it < questionnaire_result[i][1]) {
fan_id.insert(questionnaire_result[i][0]);
days_available.erase(*it);
total_questionaire_sum += questionnaire_result[i][2];
}
}
}
}
}
I believe my problem is in this line:
it = days_available.upper_bound(questionnaire_result[i][1]);
I've tested many possibilities and this is working in all my test cases. Unfortunately, we don't have the test cases of the platform.
Does someone see an situation that my code fails? With this I'm getting 90% of the score.
EDIT:
As Edward pointed me out, I've managed to solve the problem like this:
When reading the input added this line of code:
max_days = max_days | questionnaire_result[i][1];
And then did this:
for (int j = 1; j < max_days + 1; j++) {
days_available.insert(j);
}
Problem solved
This input file will cause the program to generate an incorrect result:
2
1 2 6
2 2 5
Both fans are available either day, so it's clear that both fans could be visited and the total output score should be 11. Your algorithm, however, only chooses the first one and outputs a score of 6.
I am using MongoDB 2.4.5 64 bit on Linux using C++ API to insert 1 M record
I did turn on write concern after the connection
mongo.setWriteConcern(mongo::W_NORMAL);
for (int i=0; i<RECORDS; i++) {
mongo::BSONObj record = BSON (
"_id" << i <<
"mystring" << "hello world" );
bulk_data.push_back(record);
if (i % 10000 == 0) {
mongo.insert("insert_test.col1", bulk_data);
}
}
Surprisingly at the end when I do count (via count(), it only shows 990001 records from collection 'insert_test.col1'.
What did I do wrong? Thanks for your help.
You're missing mongo.insert("insert_test.col1", bulk_data); at the end of (immediately after) your loop -- unless RECORDS is one less than a multiple of 10000 (you said it was 1000000, which isn't), then the last 9999 iterations are not inserted because they're still in bulk_data!
In other words, i is only 999999 on the last iteration through the loop, so the if isn't entered, and the last 9999 records that were put in bulk_data are not inserted.
Also, bulk_data needs to be cleared after being inserted:
if (i % 10000 == 0) {
mongo.insert("insert_test.col1", bulk_data);
bulk_data.clear(); // <-----
}