Project Euler 22

Problem 22

  • MatchCollection と Linq を連携させるには、Cast<Match>() が必要。
  • Linqメソッドチェーンで改行するさい、インデントを深くすべきか考え中。
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Linq;

class PE022 {
    static void Main() {
        var s = File.ReadAllText("../data/names.txt");
        var ss = Regex.Matches(s, "[A-Z]+")
                   .Cast<Match>()
                   .Select(e => e.Value)
                   .OrderBy(e => e);

        int ans = 0;
        int p = 1;
        foreach (string t in ss) {
            int worth = t.Select(c => c - 'A' + 1).Sum();
            ans += worth * p;
            p++;
        }
        Console.WriteLine(ans);
    }
}

参考: