C# Implementation of Problem 22

View source code here on GitHub!

Includes

Problem Solution

class p0022
: Euler.IEuler
object Answer ()
 1/*
 2Project Euler Problem 22
 3
 4I had to approach this by modifying the factors function from p0003, but it
 5seemed to work fairly well.
 6
 7Problem:
 8
 9Using names.txt (right click and 'Save Link/Target As...'), a 46K text file
10containing over five-thousand first names, begin by sorting it into
11alphabetical order. Then working out the alphabetical value for each name,
12multiply this value by its alphabetical position in the list to obtain a name
13score.
14
15For example, when the list is sorted into alphabetical order, COLIN, which is
16worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would
17obtain a score of 938 × 53 = 49714.
18
19What is the total of all the name scores in the file?
20*/
21using System;
22
23namespace Euler
24{
25    public class p0022 : IEuler
26    {
27        public object Answer()
28        {
29            int answer = 0;
30            string[] names = Utilities.GetDataFileText("p0022_names.txt").Replace("\"", "").Split(',');
31            Array.Sort(names);
32            for (int i = 0; i < names.Length; i += 1)
33            {
34                int sum = 0;
35                foreach (char c in names[i])
36                    sum += c & 0x3F;
37                answer += sum * (i + 1);
38            }
39            return answer;
40        }
41    }
42}

Tags: word-problem, sorting, file-io