% Project Euler Problem 59
% https://projecteuler.net/problem=59

cipher = load('p059_cipher.txt'); % 1455 elements long
cipher_ascii = int8(cipher);

for i=1:26
    for j=1:26
        for k=1:26
            key = int8([i,j,k]+96); % +96 so that ASCII a is 1
            key = [repmat(key, 1, 485)]; % 1455/3 = 485
            plaintext_ascii = bitxor(cipher_ascii, key);
            plaintext = char(plaintext_ascii);
            if contains(plaintext, ' the ')
                fprintf('%s\n', plaintext);
                fprintf('The key is %s\n', char(key(1:3)));
                fprintf('answer = %d\n', sum(plaintext_ascii));
            end
        end
    end
end
