Names scores | Project Euler | Problem #22

URL to the problem page: https://projecteuler.net/problem=22

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?



#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;

int main() {
    string word, word3;
    char name[5164][32], name2[5164][32], tmp[32];
    long long i = 0, j = 0, a, k, biggest, counter, sum, result = 0;

    ifstream names("names.txt");
    ofstream names2("names2.txt");
    while (names >> word) {
        strcpy_s(name[i], word.c_str());
        i++;
    }
    biggest = strlen(name[0]);
    for (i = 1; i < 5163; i++) {
        if (strlen(name[i]) > biggest) {
            biggest = strlen(name[i]);
        }
    }
    for (a = 0; a < biggest; a++) {
        for (i = 0; i < 5163; i++) {
            for (j = 0; j < 5162; j++) {
                counter = 0;
                for (k = a - 1; k >= 0; k--) {
                    if (name[j + 1][k] > name[j][k]) {
                        counter++;
                    }
                }
                if (name[j][a] > name[j + 1][a] && counter == 0) {
                    strcpy_s(tmp, name[j]);
                    strcpy_s(name[j], name[j + 1]);
                    strcpy_s(name[j + 1], tmp);
                }
            }
        }
    }
    for (i = 0; i < 5163; i++) {
        names2 << name[i] << " ";
    }
    names.close();
    names2.close();
    ifstream names3("names2.txt");
    i = 0;
    while (names3 >> word3) {
        sum = 0;
        strcpy_s(name2[i], word3.c_str());
        for (a = 0; a < strlen(name2[i]); a++) {
            sum += (name2[i][a] - 64);
        }
        result += sum * (i + 1);
        i++;
    }
    cout << "Total of all the name scores in the file is  =  " << result << endl;
}



Comments

My photo
Ercan Tomac
instagram.com/ercantomac