Monday, November 17, 2008

Problem #22

This takes the exact text file they give you as input, reads each name into a vector that it keeps resizing, then sorts the vector and sums up all the numerical values for the names.


#include <iostream>
#include <ctime>
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

int sum (string);

int main()
{
clock_t start = clock();
long int total = 0;
int count = 0;
char ch;
ifstream fi;
vector<string> v;

fi.open ("names.txt");

while (!fi.eof ())
{
v.resize (v.size () + 1);
count = 0;
ch = fi.get ();
while (ch != ',' && !fi.eof ())
{
v[v.size () - 1] += ch;
ch = fi.get ();
count++;
}
}

sort (v.begin (), v.end ());

for (unsigned int i = 0; i < v.size (); i++)
total += (i + 1) * sum (v[i]);

fi.close ();

cout << total << endl
<< "Process took " << (static_cast<double> (clock()) - start) / CLOCKS_PER_SEC << " seconds." << endl;

system("pause");
return 0;
}

int sum (string str)
{
int total = 0;

for (unsigned int i = 0; i < str.size (); i++)
if (isalpha (str[i]))
total += tolower (str[i]) - 96;

return total;
}

No comments: