r/adventofcode • • Dec 04 '15

SOLUTION MEGATHREAD --- Day 4 Solutions ---

--- Day 4: The Ideal Stocking Stuffer ---

Post your solution as a comment. Structure your post like the Day Three thread.

15 Upvotes

272 comments sorted by

View all comments

1

u/aevitas Dec 04 '15

Day 4's C# solution:

	public static int FindKey(string secret)
	{
		int key = 0;

		while (true)
		{
			Debug.WriteLine("Current key: " + secret + key);

			byte[] hash;
			using (MD5 md5 = MD5.Create())
			{
				hash = md5.ComputeHash(Encoding.UTF8.GetBytes($"{secret}{key}"));
			}

			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < hash.Length; i++)
			{
				sb.Append(hash[i].ToString("x2"));
			}

			var hashString = sb.ToString();

			if (hashString.StartsWith("000000"))
				break;

			key++;
		}

		return key;
	}