对一组单词进行排序和求和会给出不正确的结果

Sorting and summation over a set of words gives incorrect result

我在使用 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 × 53 = 49714. What is the total of all the name scores in the file?

到目前为止,这是我自己无法解决的第一个欧拉问题,我也不明白我做错了什么。我将在 1532 年之前使用此解决方案做空。

这是我的代码:

using (WebClient client = new WebClient())
{
    try
    {
        tempString = client
            .DownloadString("http://projecteuler.net/project/resources/p022_names.txt")
            .Replace("\"", "");
    }
    catch (Exception)
    {
        MessageBox.Show("Error, check your internet connection!");
    }
}

string[] names = tempString.Split(',');
Array.Sort(names);
int total = 0;
for (int i = 0; i < names.Length; i++)
{
    int namescore = 0;
    foreach (char c in names[i]) { namescore += (int)c - 64; }

    total += namescore * (i + 1);
}

return total.ToString();

我认为这可能是 C# 特定的错误或怪癖?

好的,让我们一步一步地检查,尝试找出不一致的地方。我有正确答案。

初始数据:

names.Length == 5163
names.Count(w=>!Regex.IsMatch(w,"^[A-Z]+$")) == 0
names.Sum(w=>w.Length) == 30959

部分总和(在 N 个元素之后):

500: 7139561
2500: 187773540
5000: 811204450

更新:

我有一个想法:Sort 是特定于语言环境的!试试 Sort(StringComparison.Ordinal).

更新 2:

要切换文化,set thread culture or AppDomain culture 到,比方说,CultureInfo("en-US")

如您所述,您无法设置 CurrentCulture,因此设置 DefaultThreadCurrentCulture

当我使用

CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("hr-HR");

在执行任何操作之前,我得到的结果与您相同。所以,很明显,你应该使用

CultureInfo.DefaultThreadCurrentCulture = CultureInfo.GetCultureInfo("en-US");

达到预期的输出(除了评论中提到的在ToString()方法中这样做是不够的,因为它也会影响排序)。