22. Total of all the name scores in the file

Using names.doc (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?

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;

public class Problem22 {
    public void adjacent(String ss) {
        String num[] = ss.split("\\,");
        Arrays.sort(num);
        int sum = 0;
        for (int i =0 ;i<num.length;i++) {
            int n =0;
                String name = num[i];
                for (int j =1 ;j<name.length()-1;j++) {
                    n+=(name.charAt(j)-64);
                }
                sum+=n*(i+1);
        }
        System.out.println(sum);
    }

    public static void main(String[] args) {
        Problem22 p = new Problem22();
        String ss = "";
        try {
            Scanner scanner = new Scanner(new FileInputStream("names.txt"));
            ss = scanner.nextLine();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        p.adjacent(ss);
    }
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: