Search This Blog

Thursday, December 16, 2010

Euler Problem 22

So you download a list of names.. and have to order them.. then calculate a value based on the characters (a-z) and position in the list… EASY! or is it????

Yes it is… C# has all the tools for this… build a list..then sort it.. pretty much job done… the only tip is to remember that the first place in the list (pos=0) is the 1st place in the list!!!

http://projecteuler.net/index.php?section=problems&id=22

______________

static void Main(string[] args)
        {
        List<string> names = new List<string>();
     
        //all names are in 1 line!
        System.IO.StreamReader sr = new System.IO.StreamReader("o:\\names.txt");
           
        foreach (string s in sr.ReadLine().Split(','))
        {
            names.Add(s);
        }

        names.Sort();

        long wordssum=0;

        for (int i = 0; i < names.Count; i++)
        {
            wordssum += wordvalue(names[i]) * (i+1);
        }

        Console.WriteLine(wordssum);
        Console.ReadLine();

        }

    static int wordvalue(string s)
      {
        // a=1 b=2 etc
          int val=0;
         
          foreach (char c in s.ToLower())
          {
              if (c > 96 && c < 123)
              {
                  val += Convert.ToInt16(c) - 96;
              }
          }

          return val;
    }

1 comment:

Phil said...

Just for fun..I saw this in the forum after I'd posted my result... here's how it can be done in linq once you've got the names list...

int sum = names.OrderBy(n => n).Select((n, i) => n.ToUpper().ToCharArray().Sum(c => (c - 'A') + 1) * (i + 1)).Sum();