How can this code...
vector<double> _pc;
vector<int> _documentClassIds;
[...]
someMemberFunction(vector<int> const & documentIds) {
cout << "_pc[0] = "<< _pc[0]<<endl;
cout << "_pc[1] = "<< _pc[1]<<endl;
cout << "documentIds.size() = " << documentIds.size()<<endl;
// Normalize
for (auto documentId : documentIds)
_pc[_documentClassIds[documentId]] =
_pc[_documentClassIds[documentId]] / documentIds.size();
cout << "_pc[0] = "<< _pc[0]<<endl;
cout << "_pc[1] = "<< _pc[1]<<endl;
}
produce this output?
_pc[0] = 3
_pc[1] = 3
documentIds.size() = 6
_pc[0] = 0.0138889
_pc[1] = 0.0138889
I'm not sure what you think the problem is.
You have six document IDs, so your for loop runs six times. Each time it runs, it divides one of your _pc array values by six.
Since 0.0138888... is 3 divided by 216 (6^3), the calculations seem correct.
It's obvious that the selection of which _pc array entry to divide is equally distibuted so that each gets divided three times, so each ends up as:
(((3 / 6) / 6) / 6) => 0.013888...
Related
Which is the simplest way to add a number to itself incrementally until some condition is reached? In the code bellow, we can calculate when an event will occur by simply adding event_occurence to itself until we reach max_events. I know it can be done with std::IOTA and vectors, but I want it to keep it to the simplest math possible.
My idea was to use: i=1, i * number to be multiplied, for i<=some value, i++. But only the first value gets incremented correctly.
int main()
{
int curent_year = 2021;
int input_year;
int event_occurence = 4;
std::cout << "When did you watch your first World Cup?" << std::endl;
std::cin >> input_year;
int max_events = (curent_year - input_year) / event_occurence;
int last_event = input_year + (max_events * event_occurence);
int next_first_event = input_year + event_occurence;
std::cout << "Next world cup was held in " << next_first_event << "... Meanwhile, another " << max_events << " world cups took place. The last world cup took place in " << last_event <<"." << std::endl;
int i=1;
int inbetween_events = input_year + i * event_occurence;
for (int i = 1; i <= max_events; i++)
std::cout << "The were also these worlds cups held in the following years: " <<inbetween_events <<std::endl;
}
code above compiled
int i=1;
int inbetween_events = input_year + i * event_occurence;
for (int i = 1; i <= max_events; i++)
std::cout << "The were also these worlds cups held in the following years: " <<inbetween_events <<std::endl;
}
Problem 1:
You're using a local variable (counted in CPU registers) with the same name function variable that is the parent of function for (...). You declare it in there by saying "int i = 1", what means "make new temp variable name i, value = 1)
Move the "calc"
int inbetween_events = input_year + i * event_occurence;
inside the function if you want to print out series of numbers (print inbetween_events = input_year + i * event_occurence;) , or make it
for (; i <= max_events; i++)
or
for (i = 1; i <= max_events; i++)
That could work, but I can't test it :P
You could change variables' names, but then it's still pretty ineffective, because you would increment one variable inside a loop, making 2 operations instead of one.
Problem 2:
You also don't increment the "inbetween_events" in the "for" loop.
You ask it to print out that variable "i" times. You initialized that variable as output of arithmetic operation, it wont change its value unless you order it to change it.
C++ doesn't store instructions and run them later when needed. It runs them right away. So, if you want to compute the in-between events at multiple dates, you need to code it this way:
for (int i = 1; i <= max_events; i++)
// compute inbetween_events for each value of i
int inbetween_events = input_year + i * event_occurence;
std::cout << "The were also these worlds cups held in the following years: " <<inbetween_events <<std::endl;
}
You'll probably want to fix the output with something like:
// output header first
std::cout << "The were also these worlds cups held in the following years: ";
for (int i = 1; i <= max_events; i++)
// compute inbetween_events for each value of i
int inbetween_events = input_year + i * event_occurence;
// output each year with a comma and space
std::cout << inbetween_events << ", ";
}
// end the line
std::cout << std::endl;
I'm doing some algorithmics problem and I'm having trouble with managing functions, vectors and strings in C++.
I have to find a concrete path in a matrix and for that, I need to have all the different paths, so I decided to use a function. This function will check where to continue to search. Here is the code of the function:
vector<string> get_all_paths(string actual, int rows, int columns, int col_actual, int row_prev) {
vector<string> solutions;
int row_actual = (rows+row_prev-1)%rows;
for (int i = 0; i < 3; i++) {
cout << col_actual << " " << row_actual << "\n";
//cout << (dp[row_prev][col_actual+1] - matrix[row_prev][col_actual+1]) << " " << dp[row_actual][col_actual] << "\n";
if( (dp[row_prev][col_actual+1] - matrix[row_prev][col_actual+1]) == dp[row_actual][col_actual] ) {
if (col_actual > 0) {
//cout << "--" << actual << " " << row_actual << "\n";
string branch = actual + to_string(row_actual+1) + " ";
solutions = get_best_path(branch, rows, columns, col_actual-1, row_actual);
//cout << ".." << actual << "\n";
} else {
//cout << actual << " " << row_actual << "\n";
cout << actual << "\n";
string branch = actual.c_str();
branch += to_string(row_actual+1);
cout << branch << "\n";
solutions.push_back( branch );
break;
}
}
row_actual = (row_actual+1)%rows;
}
for(auto i : solutions) cout << "--" << i << "\n";
return solutions;
}
And here is the call to the method:
vector<string> solutions;
for (int i = 0; i < rows; i++) {
if (dp[i][cols-1] == min_path) {
cout << "................\n";
solutions = get_best_path( (to_string(i+1)+" "), rows, cols, cols-2, i);
for(auto i : solutions) {
reverse(i.begin(), i.end());
cout << i << "\n";
}
cout << "xxxxxxxxxxxxxxx\n";
}
}
The thing is that I'm getting three paths for a given example, which is correct, but they are all the same string, which is the last path or the last change done in variable branch.
Maybe I'm mixing a lot of concepts and maybe this has been answered a lot of times, but I've searched this and got nothing.
EDIT: I'm not getting three paths from the function, just the last one, but when printing inside the function the paths i do have three inside that function all with the same value, sorry about that.
EDIT2: The idea of the problem is to find the minimum cost path in a given matrix and, if there are more than 1, the one that is the smallest lexicographically. So given a matrix:
5 4
9 1 9 9
1 9 9 9
9 9 9 9
1 1 1 1
9 9 1 9
My approach is to use dp as a matrix with the dynamic programming results and then i try to recreate all the paths in the function above.
In this case, the dp matrix is:
9 2 11 12
1 10 11 20
9 10 11 12
1 2 3 4
9 10 3 12
And so, the best paths are:
4 4 4 4
4 5 4 4
2 1 5 4
And the one correct is the last one.
Inside my function i do get the different paths and i add them to the vector of results, but then i lose them when searching for more.
Thanks for the time if you have read this :D!
Well I think the problem is here
solutions = get_best_path(branch, rows, columns, col_actual-1, row_actual);
because that assignment replaces any solutions you might have found so far. Instead you should append any solutions returned to any that you've found so far. In other words something like this
vector<string> tmp = get_best_path(branch, rows, columns, col_actual-1, row_actual);
solutions.insert(solutions.end(), tmp.begin(), tmp.end());
But this is just intuition, I haven't tested anything.
Example: chessboard has 64 fields, starting from 1 in top uppermost left box,
row 2, column 2 means its 10th box,
row 4, column 2 means its 26th box .....so on
Formula, trick to determine Row_column no from box number or vice versa?
I guess you mean that you have 8 boxes on each row?
This might do the trick:
#include <iostream>
#include <cmath>
const int totalNrOfBoxes = 64;
const float nrOfRows = std::sqrt(totalNrOfBoxes);
std::pair<int, int> getRowAndColumn(int boxNumber) {
int rowNumber = std::ceil(boxNumber / nrOfRows);
int columnNumber = (boxNumber - 1) % (int) nrOfRows; // we do -1 to avoid getting 0 when the boxNr is 8 or 16 or 32 for example
columnNumber += 1; // we add one number to the column number because we removed one from the box number
return std::make_pair(rowNumber, columnNumber);
}
int main()
{
std::pair<int, int> rowAndColumn = getRowAndColumn(11);
std::pair<int, int> rowAndColumn2 = getRowAndColumn(64);
std::pair<int, int> rowAndColumn3 = getRowAndColumn(1);
std::pair<int, int> rowAndColumn4 = getRowAndColumn(34);
std::pair<int, int> rowAndColumn5 = getRowAndColumn(7);
std::cout << rowAndColumn.first << " " << rowAndColumn.second << std::endl;
std::cout << rowAndColumn2.first << " " << rowAndColumn2.second << std::endl;
std::cout << rowAndColumn3.first << " " << rowAndColumn3.second << std::endl;
std::cout << rowAndColumn4.first << " " << rowAndColumn4.second << std::endl;
std::cout << rowAndColumn5.first << " " << rowAndColumn5.second << std::endl;
}
gives us the following output:
2 3
8 8
1 1
5 2
1 7
So basically what we do to determine the row number, is to divide the given box number by the number of rows, and take the ceil (finds the closest integer not less than n) out of that. Example: 26 / 8 = 3.25. We know that 26 is on the 4th row, so we need to take the closest integer not less than 3.25 which is 4.
For the column number we take the remainder. So for example with 12 it would return 4. The problem is that we start counting boxes at 1, so 16 % 8 would return 0, while we do want to get a value of 8. So that is why we say boxNumber - 1 (15 % 8 which returns 7) and add 1.
The following code is designed to implement this formula:
void integrate ( double R , double E ) //radius and acceptable error, entered by user
{
int i = 1; //iterator
int n = 1; //number of rectangles
double x = 0;
double width = 0; //stores width of each rectangle
double area = 0; //stores calculated area
double error = E + 1; //stores difference between calculated area and pi*(radius)^2
while ( error > E ) //loop continues as long as error is greater than the acceptable limit entered by user
{
width = R / n; //sets the width of rectangles
area = 0; //with this line, calculated area converges to zero. without it, calculated area increases without bound
while ( i <= n )
{
x = i; //assign iterator value to a separate variable to avoid data type issues in calculation
area += width * sqrt ( pow ( R , 2.0 ) - pow ( width * ( x - 0.5 ) , 2.0 ) ); //riemann integral formula
i++;
}
n++; //increase number of rectangles by 1 to be used in next loop
area *= 4; //forumla uses one quarter of a circle, multiply by 4 to get total area
error = abs ( area - ( pi * pow ( R , 2.0 ) ) ); //error calculation
cout << " \n Calculated area = " << area << "\n" //debugging output
<< " \n Error = " << error << "\n";
cin.get();
}
cout << "\n Area: " << area << "\n" //output to user
<< "\n Error: " << error << "\n"
<< "\n Iterations: " << i << "\n";
return;
}
As the comment says, when the line "area = 0;" is included in the first loop, the area converges to zero, and when it is removed, the area increases without bound. I've been working on this one function for the better part of a week without progress. The rest of the program is completed, tested, and works fine. I have to assume that there's either an error in the logic or the math that I just can't see. Any help would be appreciated.
I hope that the comments are sufficient. I'll provided additional clarification as necessary.
(This is a self-contained function. No other part of the program affects it or is affected by it aside from the user input.)
I am working on a chapter review of a book: at the end of the chapter there are some questions/tasks which you are to complete.
I decided to do them in the format of a program rather than a text file:
#include <iostream>
int main(int argc, char* argv[]) {
std::cout << "Chapter review\n"
<< "1. Why does C++ have more than one integer type?\n"
<< "\tTo be able to represent more accurate values & save memory by only allocating what is needed for the task at hand.\n"
<< "2. Declare variables matching the following descriptions:\n"
<< "a.\tA short integer with the value 80:\n";
short myVal1 = 80;
std::cout << "\t\t\"short myVal1 = 80;\": " << myVal1 << std::endl
<< "b.\tAn unsigned int integer with the value 42,110:\n";
unsigned int myVal2 = 42110;
std::cout << "\t\t\"unsigned int myVal2 = 42110;\": " << myVal2 << std::endl
<< "c.\tAn integer with the value 3,000,000,000:\n";
float myVal3 = 3E+9;
std::cout << "\t\t\"float myVal3 = 3E+9;\": " << static_cast<unsigned int>(myVal3) << std::endl
<< "3. What safeguards does C++ provide to keep you from exceeding the limits of an integer type?\n"
<< "\tWhen it reaches maximum number it starts from the begging again (lowest point).\n"
<< "4. What is the distinction between 33L and 33?\n"
<< "\t33L is of type long, 33 is of type int.\n"
<< "5. Consider the two C++ statements that follow:\n\tchar grade = 65;\n\tchar grade = 'A';\nAre they equivalent?\n"
<< "\tYes, the ASCII decimal number for 'A' is '65'.\n"
<< "6. How could you use C++ to find out which character the code 88 represents?\nCome up with at least two ways.\n"
<< "\t1: \"static_cast<char>(88);\": " << static_cast<char>(88) << std::endl; // 1.
char myChar = 88;
std::cout << "\t2: \"char myChar = 88;\": " << myChar << std::endl // 2.
<< "\t3: \"std::cout << (char) 88;\" " << (char) 88 << std::endl // 3.
<< "\t4: \"std::cout << char (88);\": " << char (88) << std::endl // 4.
<< "7. Assigning a long value to a float can result in a rounding error. What about assigning long to double? long long to double?\n"
<< "\tlong -> double: Rounding error.\n\tlong long -> double: Significantly incorrect number and/or rounding error.\n"
<< "8. Evaluate the following expressions as C++ would:\n"
<< "a.\t8 * 9 + 2\n"
<< "\t\tMultiplication (8 * 9 = 72) -> addition (72 + 2 = 74).\n"
<< "b.\t6 * 3 / 4\n"
<< "\t\tMultiplication (6 * 3 = 18 -> division (18 / 4 = 4).\n"
<< "c.\t3 / 4 * 6\n"
<< "\t\tDivision (3 / 4 = 0) -> multiplication (0 * 6 = 0).\n"
<< "d.\t6.0 * 3 / 4\n"
<< "\t\tMultiplication (6.0 * 3 -> 18.0) -> division (18.0 / 4 = 4.5).\n"
<< "e.\t 15 % 4\n"
<< "\t\tDivision (15 / 4 = 3.75) Then returns the reminder, basically how many times can 4 go into 15 in this case that is 3 (3*4 = 12).\n"
<< "9. Suppose x1 and x2 are two type of double variables that you want to add as integers and assign to an integer variable. Construct a C++ statement for doing so. What if you wanted to add them as type double and then convert to int?\n"
<< "\t1: \"int myInt = static_cast<double>(doubleVar);\"\n\t2: \"int myInt = int (doubleVar);\".\n"
<< "10. What is the variable type for each of the following declarations?\n"
<< "a.\t\"auto cars = 15;\"\n\t\tint\n"
<< "b.\t\"auto iou = 150.37f;\"\n\t\tfloat\n"
<< "c.\t\"auto level = 'B';\"\n\t\tchar\n"
<< "d.\t\"auto crat = U'/U00002155';\"\n\t\twchar_t ?\n"
<< "e.\t\"auto fract = 8.25f/.25;\"\n\t\tfloat" << std::endl;
return 0;
}
It's been a while since I read chapter 3 due to moving/some other real life stuff.
What I am unsure about here is basically question number 3: it says safeguards as in plural.
However I am only aware of one: that it starts from the beginning again after reaching maximum value? Am I missing something here?
Let me know if you see any other errors also - I am doing this to learn after all :).
Basically I can't accept a comment as an answer so to sum it up:
There are none safeguards, I misunderstood that question which #n.m. clarified for me.
10.e was wrong as pointed out by #Jarod42, which is correct.
Thanks!
As for me "Declare variable of integer with the value 3,000,000,000" is:
unsigned anInteger = 3000000000;
cause c++ the 11th supplies 15 integer types and unsigned int is the smallest that can store such a big integer as 3 000 000 000.
C++ classifies integer overflow as "Undefined Behavior" - anything can happen as a result of it. This by itself may be called a "safeguard" (though it's a stretch), by the following thinking:
gcc has that -ftrapv compilation switch that makes your program crash when integer overflow happens. This allows you to debug your overflows easily. This feature is possible because C++ made it legal (by nature of Undefined Behavior) to make your program crash in these circumstances. I think the C++ Committee had this exact scenario in mind when making that part of the C++ Standard.
This is different from e.g. Java, where integer overflow causes wraparound, and is probably harder to debug.