Project Euler: Problem 81 – Path sum: two ways

Problem 81:

In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by only moving to the right and down, is indicated in bold red and is equal to 2427.

131 673 234 103 18
201 96 342 965 150
630 803 746 422 111
537 699 497 121 956
805 732 524 37 331

Find the minimal path sum, in matrix.txt (right click and ‘Save Link/Target As…’), a 31K text file containing a 80 by 80 matrix, from the top left to the bottom right by only moving right and down.

Idea:

This problem is identical to problem 18, except in the form of a matrix instead of tree, and I want the minimal path instead of maximum path. I modified the algorithm I used for problem 18 to go either right or down (instead of down, or down and to the right). Tested it out and it worked.

int answer = -1;
int[][] tree = EulerUtils.readMatrix("Problem_81.txt");
EulerUtils.SumTreePath path = EulerUtils.matrixPath(tree,false);
answer = path.getSum();

Project Euler: Problem 80 – Square root digital expansion

Problem 80:

It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all.
 
The square root of two is 1.41421356237309504880…, and the digital sum of the first one hundred decimal digits is 475.
 
For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots.

Idea:

Since I need a lot of digits / precision, I need to use the sister class of BigInteger: BigDecimal. I saw BigDecimal had no square root method, so I was going to use the power method, but it only accepts integers (so I can’t raise a decimal to the 1/2 power, i.e. square root). So I had to create a square root method myself (after a little research).
 
With that completed, I just needed to check to see if the resulting square root was an integer or decimal. From there, just add the first 100 decimal values together for all the non-integer square roots.

int answer = 0;

MathContext precision = new MathContext(105);
for(int i = 1; i <= 100; i++) {
    BigDecimal temp = EulerUtils.sqrt(BigDecimal.valueOf(i), precision);
    String number = temp.toString();
    if(number.indexOf(".") == -1) {
        continue;
    } else {
        number = number.substring(0,101);
        number = number.replace(".","");
        for(char c:number.toCharArray()) {
            answer += Integer.parseInt(""+c);
        }
    }
}

Note: sqrt() is a method I wrote to calculate the square root of a BigDecimal up to a given precision.

Project Euler: Problem 67 – Maximum path sum II

Problem 67:

By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

3
7 4
2 4 6
8 5 9 3

 
That is, 3 + 7 + 4 + 9 = 23.
 
Find the maximum total from top to bottom in triangle.txt (right click and ‘Save Link/Target As…’), a 15K text file containing a triangle with one-hundred rows.
 
NOTE: This is a much more difficult version of Problem 18 (and my attempt). It is not possible to try every route to solve this problem, as there are 299altogether! If you could check one trillion (1012) routes every second it would take over twenty billion years to check them all. There is an efficient algorithm to solve it. ;o)

Idea:

Since I already did the work for this on problem 18, I decided to just do what I did for that problem, and sure enough, it worked rather quickly. On my computer, less than a second.

int answer = -1;

int[][] tree = EulerUtils.readMatrix("Problem_67.txt");
long start = System.currentTimeMillis();
EulerUtils.SumTreePath path = EulerUtils.treePath(tree,true);
long end = System.currentTimeMillis();
System.out.println("Start: "+start+"\tEnd: "+end);
answer = path.getSum();

Project Euler: Problem 59 – XOR decryption

Problem 59:

Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (*) = 42, and lowercase k = 107.
 
A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
 
For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both “halves”, it is impossible to decrypt the message.
 
Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.
 
Your task has been made easy, as the encryption key consists of three lower case characters. Using cipher1.txt (right click and ‘Save Link/Target As…’), a file containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.

Idea:

Since the problem said the words would be in common English, I had two options after running the decryption: look for words, or analyze letter frequency. Not knowing what kind of words the text would contain, I didn’t think it was feasible to search for a bunch of words in the decrypted text and hopefully hit a match. Instead I opted to analyze letter frequency, so I used the table from Letter frequency Wikipedia page.
 
I figured, however, that certain decryption keys would yield similar letter frequencies but produce garbled results. I decided I would do a comparison of frequency on, and add up the discrepancy of, each letter to get an overall discrepancy. I stored each overall discrepancy along with the key that produced it, just in case the key with the smallest overall discrepancy did not produce a decrypted text.
 
Once I had the key that produced the smallest overall discrepancy, I decrypted the text again and printed it to the console to see if that was the proper key, or if I needed to pick the 2nd smallest, or 3rd smallest, and so on.

int answer = 0;

int[] encrypted;
{
   List<String> tmp = EulerUtils.readFile22("Problem_59.txt");
   encrypted = new int[tmp.size()];
   for(int i = 0; i < tmp.size(); i++) {
      encrypted[i] = Integer.parseInt(tmp.get(i));
   }
}

int[] cypher = {'a','a','a'};

String easyKey = "";
int[] key = new int[3];
double variance = 1.0;
for(int a = 0; a < 26; a++) {
   cypher[0] = 'a'+a;
   for(int b = 0; b < 26; b++) {
      cypher[1] = 'a'+b;   
      for(int c = 0; c < 26; c++) {
         cypher[2] = 'a'+c;
         int[] decrypted = EulerUtils.decrypt(encrypted,cypher);
         double analyzed = EulerUtils.analyzeLetterFrequency(decrypted);
         if(analyzed < variance) {
            variance = analyzed;
            easyKey = ""+(char)cypher[0]+(char)cypher[1]+(char)cypher[2];
            key[0] = cypher[0];
            key[1] = cypher[1];
            key[2] = cypher[2];
         }
         analysis.put(""+cypher[0]+cypher[1]+cypher[2], analyzed);
      }
   }
}

System.out.println("EasyKey = "+easyKey+
            ";Total Frequency Difference = "+variance*100.0+"%");
System.out.println("Key: "+key[0]+","+key[1]+","+key[2]);
int[] decrypted = EulerUtils.decrypt(encrypted,key);
System.out.println(EulerUtils.asciiToString(decrypted));

for(int i : decrypted)
   answer+=i;

Note:
decrypt() takes the encrypted ASCII code text and XOR’s it with the supplied cypher key.
analyzeLetterFrequency() takes ASCII coded text (int array) and analyzes the overall discrepancy.
asciiToString() simply converts ASCII coded text (int array) to a String.