Skip to content

Instantly share code, notes, and snippets.

@bencoveney
Created August 4, 2014 08:53
Show Gist options
  • Save bencoveney/876e8a98984c286b50bc to your computer and use it in GitHub Desktop.
Save bencoveney/876e8a98984c286b50bc to your computer and use it in GitHub Desktop.
Names scores
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
using System.Threading.Tasks;
namespace EulerProject
{
class Program
{
/// <summary>
/// The letter scores
/// </summary>
private static Dictionary<char, int> letterScores;
/// <summary>
/// Mains the specified arguments.
/// </summary>
/// <param name="args">The arguments.</param>
[STAThread]
static void Main(string[] args)
{
// get the value of each letter in the alphabet
char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
letterScores = new Dictionary<char,int>();
for (int i = 0; i < alpha.Length; i++)
{
letterScores.Add(alpha[i], i+1);
}
// Read all names from file
List<string> names = new List<string>();
File.ReadAllText("names.txt").Split(',').ToList().ForEach(x => names.Add(x.Replace("\"", "")));
// Sort alphabetically
names.Sort(StringComparer.InvariantCultureIgnoreCase);
// Calculate scores for each name
int iterator = 1;
List<long> scores = new List<long>();
names.ForEach(x => scores.Add(calculateScore(x) * iterator++));
// Sum every name's score
long scoreSum = 0;
scores.ToList().ForEach(x => scoreSum += x);
// Show the result
Console.WriteLine(scoreSum);
System.Windows.Forms.Clipboard.SetText(scoreSum.ToString());
Console.Read();
}
/// <summary>
/// Calculates the sum of letter scores in a string
/// </summary>
/// <param name="name">The name.</param>
/// <returns>The score</returns>
private static int calculateScore(string name)
{
// Check the letter scores exist
if (letterScores == null) throw new NullReferenceException("letterScores hasn't been created");
// Calculate the score sum
int score = 0;
name.ToCharArray().ToList().ForEach(x => score += letterScores[x]);
return score;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment