Euler Project 11

c++

Solution

The indices for the diagonals are wrong. For example:

... * grid.at(i-1).at(j+1) * grid.at(i-1).at(j+2) * grid.at(i -3).at(j+3))

The middle part should have `i-2` instead of `i-1`. Similar issues with the other diagonals.

Problem

I'm busy with Project Euler, and i'm trying to solve problem 11, but the answer seems to be faulty. But I don't understand why, the code seems to be right. ``` vector<vector<int> > grid; ifstream stream("/home/uauser/workspace/Project_euler/grid.txt"); string line; char *tok; if (stream.is_open()) { while(stream.good()) { getline(stream, line); tok = strtok((char *)line.c_str(), " "); vector<int> row; while (tok != NULL) { int field; stringstream ss; ss << tok; ss >> field; row.push_back(field); tok = strtok(NULL, " "); } grid.push_back(row); } stream.close(); } int product = 0; for(unsigned int i = 0; i < grid.size(); i++) { for(unsigned int j = 0; j < grid.at(i).size(); j++) { if( i < 17) { product = max(product, grid.at(i).at(j) * grid.at(i + 1).at(j) * grid.at(i + 2).at(j) * grid.at(i + 3).at(j)); } if( j < 17) { product = max(product, grid.at(i).at(j) * grid.at(i).at(j+1)* grid.at(i).at(j+2) * grid.at(i).at(j + 3)); } if((j < 17) && (i < 17) && (j >= 3) && (i >= 3)) { product = max(product, grid.at(i).at(j) * grid.at(i-1).at(j+1) * grid.at(i-1).at(j+2) * grid.at(i -3).at(j+3)); product = max(product, grid.at(i).at(j) * grid.at(i+1).at(j-1) * grid.at(i+1).at(j-2) * grid.at(i +3).at(j-3)); product = max(product, grid.at(i).at(j) * grid.at(i+1).at(j+1) * grid.at(i+1).at(j+2) * grid.at(i + 3).at(j + 3)); product = max(product, grid.at(i).at(j) * grid.at(i-1).at(j-1) * grid.at(i-1).at(j-2) * grid.at(i -3).at(j-3)); } cout<<product<<endl; } } cout<<"The Product is: "<<product<<endl; } ``` sow the code read's the txt file without a problem, but when he need to find the max value is only get the wrong answer.

Original source

Related problems