Friday, November 8, 2013

Problem 59 - C# again

Despite the fact that this is the second C# solution in about 5 solutions, I really am not a huge fan of the language - It is a nice language with C-like syntax though which I had yet to use for a hard enough problem that it was attractive to continue uprooting it. This problem was mildly annoying though, require things like file i/o that can sometimes be frustrating or near-impossible with more esoteric languages. This problem involves XOR encryption of a file, and you must brute-force find a key for the message. Though I remembered the message and key from the last time I solved this problem, I didn't take any advantage of that knowledge in my solution, as indicated by the fact that my test for correctness is simply containing " the " somewhere in the message. Anyway, this should put C# to rest for a while...solution runs in 2 seconds, but I could probably speed it up if I wanted to by not re-reading the file on every key. Also, for anyone checking my solutions, I reformatted the input file to have one number per line.
using System.IO;
public class Euler59 {
    
    public static char[] decode(char[] key) {
        StreamReader reader = new StreamReader("cipher1.txt");
        char[] message = new char[1201];
        int i = 0;
        do {
            char c = (char) System.Convert.ToInt16(reader.ReadLine());
            message[i] = (char)(((int)c) ^ ((int)key[i%3]));
            i++;
        } while (reader.Peek() != -1);
        return message;
    }


    public static int Main(string[] args) {
        for (char a = 'a'; a <= 'z'; ++a) {
            for (char b = 'a'; b <= 'z'; ++b) {
                for (char c = 'b'; c <= 'z'; ++c) {
                    char[] key = new char[3] {a,b,c};
                    char[] asciis = decode(key);
                    string message = new string(asciis);
                    if (message.Contains(" the ")) {
                        int ans = 0;
                        for (int i = 0; i < asciis.Length; ++i) {
                            ans += (int) asciis[i];
                        }
                        System.Console.WriteLine(ans);
                        return 0;
                    }
                }
            }
        }
        return 0;
    }
}

No comments:

Post a Comment