Henrik Hollósi Henrik Hollósi - 2 months ago 12
C# Question

What's the matter with my code?

I'm trying to solve Project Euler problem 22 in C#. After a lot of debugging I still think that my code is correct but the end result is still somehow incorrect. What am I doing wrong?

Code:

string[] namesList = null;
long totalScore = 0;
using (var reader = new StreamReader("names.txt"))
{
string names;
names = reader.ReadToEnd();
namesList = names.Split(',');
for (int i = 0; i < namesList.Length; i++)
namesList[i] = namesList[i].Trim('"');
}

Array.Sort(namesList);

for (int i = 0; i < namesList.Length; i++)
{
int nameScore = 0;
foreach (var c in namesList[i])
{
nameScore += c - 'A' + 1;
}
nameScore *= i + 1;
totalScore += nameScore;
}

Console.WriteLine(totalScore);


Problem description: https://projecteuler.net/problem=22

Answer

Your solution works fine at least on my PC with English (US) Culture. It gives the correct result for "COLIN" which is 49714 and total result is also absolutely correct.

Alternative culture-safe way would be:

string[] names = File.ReadAllText("p022_names.txt").Split(',')
                     .Select(x => x.Trim('"')).ToArray();

Array.Sort(names, StringComparer.InvariantCulture);

int index = 1;
int totalScore = 0;
foreach (var name in names)
{
    totalScore += index * name.Sum(c => char.ToUpper(c) - 64);
    index++;
}
Console.WriteLine(totalScore);