Euler Problem 22

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?

This one was fun. You’ve got to load in the text file (which is one big String BTW), parse it, sort it, add up each letter value and then multiply by the location. I kept checking results against the COLIN example to make sure my code was working.

import java.util.*;
import java.io.*;

public class Euler22
{
    public static void main(String[] args)
    {
        System.out.print(“Problem 22:\n”);
        Euler22 e = new Euler22();
        System.out.print(“Answer = ” + e.Problem()+ “\n”);
    }
    public String Problem ()
    {
        ArrayList<String> names = new ArrayList<String>();
        ArrayList<Integer> scores = new ArrayList<Integer>();
        String list= “”, line = “”;
        int holder = 0;
        long sum = 0;
        try
        {
            FileInputStream stream = new FileInputStream(“F:/Development/Java/EULER/src/euler/names.txt”);
            DataInputStream in = new DataInputStream(stream);
            BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
            while ((line = buffer.readLine()) != null)
                list = line;
            in.close();
        }
        catch (Exception e)
        {
              System.out.print(e+”\n”);
        }
        for (String n : list.split(“,”))
        {
            names.add(n);
            scores.add(0);
        }
        Collections.sort(names);
        for (int i = 0; i <= names.size()-1; i++)
        {
            for (int c = 0; c <= names.get(i).length()-1; c++)
            {
                holder = scores.get(i);
                if (names.get(i).charAt(c) != 34)
                {
                    scores.remove(i);
                    scores.add(i, holder + names.get(i).charAt(c)-64);
                }
            }
            holder = scores.get(i)*(i+1);
            scores.remove(i);
            scores.add(i, holder);
        }
        for (int s : scores)
            sum += s;
        return String.valueOf(sum);
    }
}

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