Saturday 11 April 2009

PROJECT EULER #22

Link to Project 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 x 53 = 49714.

What is the total of all the name scores in the file?


I live and work in Norway, where 'CAA' comes after 'CAZ' in the alphabet (because we have the letter 'Å' here which can be written 'AA' and which comes after 'Z'). This meant that I had to change the CurrentCulture settings to English to make this work.



using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
using System.Threading;

namespace ProjectEuler
{
class Program
{
static void Main()
{
//Problem 22
DateTime start = DateTime.Now;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
StreamReader sr = new StreamReader(@"../../names.txt");
string s = sr.ReadToEnd().Replace('"',' ').ToUpper();
char[] c = {','};
string[] split = s.Split(c);
List<string> names = new List<string>();
long sum=0;
for (int i = 0; i < split.Length; i++)
{
names.Add(split[i].Trim());
}
names.Sort();
for (int i = names.Count-1; i >=0 ; i--)
{
int value=0;
char[] d = names[i].ToCharArray();
foreach (char c1 in d)
{
value += c1-64;
}
value *= (i+1);
sum += value;
}
Console.WriteLine(sum);
TimeSpan time = DateTime.Now-start;
Console.WriteLine("This took {0}", time);
Console.ReadKey();
}
}
}

No comments: