From bebd257ef7e119299e7e51ad929e18883822a11c Mon Sep 17 00:00:00 2001 From: Jake Date: Sat, 3 Dec 2022 15:40:06 +0000 Subject: [PATCH] Completed 2015 day 4 --- 2015/Day-04/Day04.cs | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 2015/Day-04/Day04.cs diff --git a/2015/Day-04/Day04.cs b/2015/Day-04/Day04.cs new file mode 100644 index 0000000..fff6c39 --- /dev/null +++ b/2015/Day-04/Day04.cs @@ -0,0 +1,57 @@ +using System.Security.Cryptography; +using System.Text; + +// Placeholders for values that need to be updated by multiple threads. +int nextNum; +int theNumber; + +// Read the input into a string. +string input = File.ReadAllText(@"input.txt").ToString(); + +// Generate an MD5 from our input plus a number. Update the global var if MD5 matches goal. +bool checkMD5(int num, string goal){ + string currentMd5 = new string('x', goal.Count()); + using (MD5 md5 = MD5.Create()){ + byte[] hashBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(input+num.ToString())); + var sBuilder = new StringBuilder(); + for (int i = 0; i < hashBytes.Length; i++) + { + sBuilder.Append(hashBytes[i].ToString("x2")); + } + currentMd5 = sBuilder.ToString(); + } + if(currentMd5.Substring(0,goal.Count()) == goal && theNumber == 0){ + theNumber = num; + return true; + } + return false; +} + +// Keep running checkMD5 incrementing the number it appends each time. +void mine(string goal){ + while(checkMD5(nextNum, goal) == false && theNumber == 0){ + nextNum++; + } +} + +// Start n threads all running the mine function for a given goal +int startThreads(string goal, int numThreads){ + theNumber = 0; + nextNum = 0; + for(int i = 0; i < numThreads; i++){ + Thread thread = new Thread(() => mine(goal)){ + Name = "thread" + "_" + goal + i.ToString() + }; + thread.Start(); + } + while(theNumber == 0){ + + } + return theNumber; +} + +// Print the result. +DateTime start = DateTime.Now; +Console.WriteLine("Part 1: " + startThreads("00000", 4)); +Console.WriteLine("Part 2: " + startThreads("000000", 4)); +Console.WriteLine("Time taken: " + DateTime.Now.Subtract(start));