Project Euler

A Taste of Number Theory

Problem 22: Name Scores

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 x 3 = 49714. What is the total of all the name scores in the file?

The Catch

How to read all the name inputs from names.txt How to sort the inputs in alphabetical order.
How to efficiently determine the order of each letter in the alphabet.

The Light

Use Java's Scanner class and split the inputs by commas (,) and then strip the opening and closing quotation marks.

Sorting is a very interesting topic, which will be discussed later. As for now, use Arrays class' built-in sort method.

Each letter has its own unique American Standard Code for Information Interchange (ASCII) code, which can be used to find the order of a letter in the alphabet. To find the order of a letter in the alphabet, subtract its ASCII code from that of the letter 'A', which is the first letter in the alphabet, then add 1. For example, the ASCII code of the letter 'A' is 65 and that of 'L' is 76, so the order of 'L' in the alphabet is 76 - 65 + 1 = 12. To find the ASCII code of a character in Java, simply do a type cast from a type char to a type int. ascii

The Code

import java.util.*;

public class Problem22
  public static void main(String[] args) throws FileNotFoundException
    File name = new File("names.txt");
    Scanner scan = new Scanner(name);

    String string = scan.nextLine();
    String[] s = string.split(",");

    for(int i = 0; i < s.length; i++)
      s[i] = s[i].substring(1, s[i].length() - 1);

    char a = 'A';
    int first = (int)a;
    int total = 0;

    for(int i = 0; i < s.length; i++)
      char[] c = s[i].toCharArray();
      int score = 0;
      for(int y = 0; y < c.length; y++)
        int tmp = (int)c[y];
        int order = tmp - first + 1;
        score += order;
      score *= (i + 1);
      total += score;