Posted By

omarelsaid on 04/09/14


Tagged


Versions (?)

Sum of name scores


 / Published in: C++
 

Reads in a comma separated text file of names and computes the total name score of all the names in the file.

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.

Doing this for all the names in the text file and summing the scores is the objective of this code.

  1. #define _SCL_SECURE_NO_WARNINGS
  2.  
  3. #include <iostream>
  4. #include <fstream>
  5. #include <vector>
  6. #include <boost/algorithm/string.hpp>
  7. #include <algorithm>
  8.  
  9. void main()
  10. {
  11. //read in a comma separated list of names, with quotation marks. e.g
  12. //"ANTHONY","JAMES","TOM",... etc
  13. std::ifstream ifs("./names.txt");
  14. std::vector<std::string> names;
  15. std::string line;
  16. while (std::getline(ifs, line))
  17. boost::split(names, line, boost::is_any_of(","));
  18.  
  19. std::stable_sort(names.begin(), names.end());
  20. unsigned long long int scoreSum = 0;
  21. for (unsigned int i = 0; i < names.size(); ++i)
  22. {
  23. unsigned int sum = 0;
  24. for (unsigned int j = 1; j < names[i].size() - 1; ++j)
  25. sum += names[i][j] - 'A' + 1;
  26.  
  27. scoreSum += sum * (i + 1);
  28. }
  29.  
  30. std::cout << scoreSum << std::endl;
  31. system("pause");
  32. }

Report this snippet  

You need to login to post a comment.