Project Euler #22: Names scores | Hackerrank | Project Euler

 Names scores

You are given around 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 in sample is sorted into alphabetical order, PAMELA, which is worth 16 + 1 + 13 + 5 + 12 +1 = 48, is the 5th name in the list. So, PAMELA would obtain a score of 5*48=240.

You are given Q queries, each query is a name, you have to print the score.

Input Format

The first line contains an integer N, i.e., number of names.
Next N lines will contain a Name.
Followed by integer Q followed by Q lines each having a word.

Constraints

1<=N<=5200
length of each word will be less than 
1<=Q<=100

Output Format

Print the values corresponding to each test case.

Sample Input

5
ALEX
LUIS
JAMES
BRIAN
PAMELA
1
PAMELA


Sample Output

240


Solution:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int getIndex(vector<string> names, string K)
{
    auto it = find(names.begin(), names.end(), K);
    if (it != names.end()) 
    {
        int index = it - names.begin();
        return index ;
    }
    else {
        return -1 ;
    }
}
bool mycomp(string a, string b){
    return a<b;
}
vector<string> alphabaticallySort(vector<string> a){
    int n=a.size();
    sort(a.begin(),a.end(),mycomp);
    return a;
}
int main()
{   
    int n,q;
    scanf("%d",&n);
    vector<string> names;
    string name;
    for(int i=0;i<n;i++){
        cin>>name;
        names.push_back(name); 
    }
    names=alphabaticallySort(names);
    scanf("%d",&q);
    for(int q1=0;q1<q;q1++)
    {
      string query;
      int ind,sum=0;
      cin>>query;
      ind=getIndex(names, query);
      for(int j=0;j<query.length();j++)
            sum+=(int)(query[j])-64;
      cout<<sum*(ind+1)<<endl;   
    }
    return 0;
}


You can also run it on an online IDE :


Your feedback are always welcome! If you have any doubt you 
can contact me or leave a comment!  
Happy Coding!! Cheers!!!

No comments:

Post a Comment

Super Market Problem | TCS Code Vita 2023 - Zone 1 | Super Market TCS Code Vita 2023 Solution | Code Vita 2023 | Code Vita 2023 season 11 solution

 Problem Description: In a Super market we will find many variations of the same product. In the same way we can find many types of rice bag...