Java Implementation of Problem 22

View source code here on GitHub!

Includes

Problem Solution

public class p0022 implements IEuler
Object answer()
Returns:

The answer to Project Euler problem 22

 1/*
 2Project Euler Problem 22
 3
 4Porting my file reader from C# was a bit more troublesome than I expected
 5
 6Problem:
 7
 8Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
 9containing over five-thousand first names, begin by sorting it into
10alphabetical order. Then working out the alphabetical value for each name,
11multiply this value by its alphabetical position in the list to obtain a name
12score.
13
14For example, when the list is sorted into alphabetical order, COLIN, which is
15worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
16obtain a score of 938 × 53 = 49714.
17
18What is the total of all the name scores in the file?
19*/
20package euler;
21
22import java.io.IOException;
23import java.util.Arrays;
24
25import euler.lib.Utilities;
26
27public class p0022 implements IEuler {
28    @Override
29    public Object answer() {
30        int answer = 0;
31        String[] names;
32        try {
33            names = Utilities.getDataFileText("p0022_names.txt")
34                             .replace("\"", "")
35                             .split(",", 0);
36        } catch (IOException e) {
37            return null;
38        }
39        Arrays.sort(names);
40        for (int i = 0; i < names.length; i += 1) {
41            int sum = 0;
42            for (int j = 0; j < names[i].length(); j += 1)
43                sum += names[i].charAt(j) & 0x3F;
44            answer += sum * (i + 1);
45        }
46        return answer;
47    }
48}

Tags: file-io, word-problem, sorting