Compilers give different answers for Project Euler # 22

I am doing Project Euler # 22:

Using names.txt (right click and "Save link / target as ..."), text 46 KB file containing more than five thousand first names, start by sorting in alphabetical order. Then we develop an alphabetical value for each name, multiply this value by its alphabetical position in order to get a name rating.

For example, when a list is sorted alphabetically, COLIN, which costs 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. Thus, COLIN will receive a score of 938 Γ— 53 = 49714.

What is the total amount of all the names in the file?

Compiling my code below using the Cygwin gcc-g ++ compiler, answer 871129635 . But with Visual Studio 2008, the answer is correct, 871198282 . Why is this so?

 #include<iostream> #include<fstream> #include<vector> #include<algorithm> using namespace std; bool strCmp(string x, string y) { if(x.compare(y) == -1) return true; else return false; } int getScore(string s) { int score = 0; for(unsigned int i = 0; i < s.length(); i++) score += (((int) s.at(i)) - 64); return score; } int getTotalScore(vector<string> names) { int total = 0; for(unsigned int i = 0; i < names.size(); i++) total += (getScore(names[i]) * (i+1)); return total; } int main() { vector<string> names; ifstream namesFile("names.txt"); char curChar; string curName = ""; //get names from file if(namesFile.is_open()) { while(!namesFile.eof()) { curChar = namesFile.get(); if(isalpha(curChar)) curName.push_back(curChar); else { if(!curName.empty()) {//store finished name names.push_back(curName); curName.clear(); } } } } namesFile.close(); //alphabetize sort(names.begin(), names.end(), strCmp); //count up name scores cout << getTotalScore(names) << endl; return 0; } 
+6
source share
1 answer

Here:

 if(x.compare(y) == -1) 

You assume that std::string::compare will return -1 for the result less than the result, but can actually return a negative value. You can fix this using x.compare(y) < 0 , but it's better to just write x<y . Actually, you don’t even need the strCmp function, because the default behavior of std::sort is to compare elements with operator< .

+9
source

Source: https://habr.com/ru/post/892695/


All Articles