Problem 22
Statement
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?
Solution
The code, in C.
#include <stdio.h>
int isbigger(char *n1, char *n2)
{
while(*n1!=0 &amp;&amp; *n2!=0){
if(*n1>*n2)
return 1;
else if(*n1<*n2)
return 0;
else{
n1++;
n2++;
}
}
if(!*n2)
return 1;
return 0;
}
void sort(char *names[], int n)
{
int i,j;
char *tmp;
for(i=n-1;i>=0;i--)
for(j=1;j<=i;j++){
if(isbigger(names[j-1],names[j])){
tmp=names[j];
names[j]=names[j-1];
names[j-1]=tmp;
}
}
return;
}
long long int eval(char *names[], int n)
{
int i,j;
unsigned long long int s=0;
for(i=0;i<n;i++)
for(j=0;names[i][j];j++)
s+=((names[i][j]-'A'+1)*(i+1));
return s;
}
int main(void)
{
int n=5163;
char *names[]={(content of the text file)};
sort(names,n);
printf("%lld\n",eval(names,n));
return 0;
}
Answer
871198282
SPEAK / ADD YOUR COMMENT
Comments are moderated.
Posts