Project Euler #22: Names scores

  • + 0 comments

    using System; using System.Collections.Generic;

    class Solution { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); string[] str = new string[n];

        SortedDictionary<string, int> sorted = new SortedDictionary<string, int>();
    
        for (int i = 0; i < n; i++)
        {
            int sum = 0;
    
            str[i] = Console.ReadLine();
            char[] characters = str[i].ToCharArray();
            foreach (char ch in characters)
            {
                sum += (int)ch - 64; // - 64 because the ASCII value of 'A' is 65, so 'A' - 64 = 1
            }
            sorted[str[i].ToUpper()] = sum;
        }
    
        // to get the key and value of SortedDictionary using Index
        var entryArray = new KeyValuePair<string, int>[sorted.Count];
        sorted.CopyTo(entryArray, 0);
    
        // updating the assigned value to names after sorted position. This is why case 1 fails
        for (int i = 0; i < sorted.Count; i++)
        {
            int newNumber = entryArray[i].Value * (i + 1);
            sorted[entryArray[i].Key] = newNumber;
        }
    
        int q = int.Parse(Console.ReadLine());
    
        for (int i = 0; i < q; i++)
        {
            string name = Console.ReadLine();
            if (sorted.ContainsKey(name.ToUpper()))
            {
                Console.WriteLine(sorted[name.ToUpper()]);
            }
        }
    }
    

    }