Problem 22
Names scores
Problem 22
19 July 2002
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714.
What is the total of all the name scores in the file?
1 #include "pub.h" 2 #include <fstream> 3 #include <vector> 4 #include <algorithm> 5 /* 6 *Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, 7 *begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply 8 *this value by its alphabetical position in the list to obtain a name score. 9 10 *For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, 11 *is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714. 12 13 *What is the total of all the name scores in the file? 14 */ 15 void p22() 16 { 17 ifstream file("D:\\study\\My_Program\\haa\\tt-build-Desktop-Release\\release\\names.txt"); 18 if (!file) { 19 cerr << "can't open input file "<< endl; 20 return; 21 } 22 char c; 23 string name=""; 24 vector<string> names; 25 int i=1; 26 while (file.get(c)) { 27 if(c=='"') 28 continue; 29 else if(c==','){ 30 names.push_back(name); 31 name=""; 32 } 33 else{ 34 name+=c; 35 } 36 } 37 names.push_back(name); 38 sort(names.begin(),names.end()); 39 long num_total=0; 40 for(int i=0;i<names.size();++i){ 41 long num_sum=0; 42 for(int j=0;j<names[i].length();j++) 43 num_sum+=(names[i][j]-'A'+1); 44 num_total+=num_sum*(i+1); 45 } 46 cout<<num_total<<endl; 47 }