Self-hatred

Project Euler Problem #22

My stroke of brilliance:

c += ((b[i] - '0') + 10) % 26;
  • Take b[i]. In this example make it the letter ‘A’.
  • Subtract ’0′. You are left with. 17.
  • Add 10. It becomes 27.
  • Modulo 26. It returns 1.

Works for every other letter (although you have to change the value of “z” to 26).

using System;
using System.IO;

public class TwentyTwo
{
	static void Main()
	{
		string[]   a = Import("22.txt");
		long       b = 0;

		for (int i = 0; i < a.Length; i++)
			b += Tally(a[i]) * (i + 1);

		Console.WriteLine("\n{0}\n", b);
	}

	static int Tally(string a)
	{
		char[] b = a.ToCharArray();
		int    c = 0;
		int    d = 0;

		for (int i = 0; i < b.Length; i++)
		{
			c = ((b[i] - '0') + 10) % 26;
			if (c == 0)
				c = 26;
			d += c;
		}

		return d;
	}

	static string[] Import(string path)
	{
		string[] a = File.ReadAllLines(path);
		string[] b = a[0].Split(',');
		Array.Sort(b);
		return b;
	}
}

Categorised as: programming


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>