sunday~

Project Euler problem 22~

  1:     class Program
  2:     {
  3:         static void Main(string[] args)
  4:         {
  5:             var sw = new Stopwatch();
  6: 
  7:             Console.WriteLine("The total of all the name scores in the file?");
  8:             sw.Start();
  9:             var sum1 = test();
 10:             sw.Stop();
 11:             Console.WriteLine(string.Format("plain read-sort-calculate way(tick:{0}): {1}", sw.ElapsedTicks, sum1));
 12: 
 13:             sw.Reset();
 14: 
 15:             Console.WriteLine("Press any key to exit");
 16:             Console.ReadKey();
 17:         }
 18:         static readonly int ASCIIA = 96; //since in this case a = 1
 19:         /// <summary>
 20:         /// looks like the built-in sort is quick sort
 21:         /// http://msdn.microsoft.com/en-us/library/b0zbh7b6%28VS.96%29.aspx
 22:         /// </summary>
 23:         /// <returns></returns>
 24:         static long test()
 25:         {
 26:             var list = new List<string>();
 27: 
 28:             using (StreamReader sr = new StreamReader("names.txt"))
 29:             {
 30:                 String line;
 31:                 // Read and display lines from the file until the end of 
 32:                 // the file is reached.
 33:                 while ((line = sr.ReadLine()) != null)
 34:                 {
 35:                     foreach (var item in line.Split(','))
 36:                     {
 37:                         list.Add(item.Substring(1, item.Length - 2).ToLowerInvariant());
 38:                     }
 39: 
 40:                 }
 41:             }
 42:             list.Sort();
 43:             long sum = 0;
 44:             long local = 0;
 45:             for (int i = 0; i < list.Count; i++)
 46:             {
 47:                 local = 0;
 48:                 local = list[i].ToCharArray()
 49:                     .Aggregate(local, (s, c) => s += (Convert.ToByte(c) - ASCIIA));
 50:                 sum += (local * (i + 1));
 51:             }
 52:             return sum;
 53:         }
 54:     }

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s