Problem specification: ProjectEuler.net Problem 67
Calculating the path from the top to the bottom to find the largest - you will have to expand a large number of nodes in the search as you cannot discount nodes to be guaranteed you found the correct answer
The solution is to work from the bottom, whereby the node above is the sum of the node above and the greater of it's two children. That is exactly what this solution does, starts from the bottom and works upwards...
Execution time: 152ms (laptop)
CODE
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Project euler problem 67 java solution
* @author Mike
*/
public class Problem_67 {
public static void main(String[] args){
String[] lines = new String[100];
Scanner scan;
try {
scan = new Scanner(new File("C:\\triangle.txt"));
int lineNo = 0;
while(scan.hasNext()){
lines[lineNo] = scan.nextLine();
lineNo++;
}
for(int i = lines.length - 2; i >= 0; i--){
String[] vals = lines[i].split(" ");
String[] belowVals = lines[i + 1].split(" ");
for(int pos = 0; pos <= vals.length - 1; pos++){
vals[pos] = String.valueOf(Integer.valueOf(vals[pos]) + Math.max(Integer.valueOf(belowVals[pos]), Integer.valueOf(belowVals[pos + 1])));
}
// Re-write the line...
lines[i] = "";
for(int k = 0; k < vals.length; k++){
lines[i] += vals[k];
if(k < vals.length - 1){
lines[i] += " ";
}
}
}
System.out.println(lines[0]);
} catch (FileNotFoundException ex) {
Logger.getLogger(Problem_67.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Any suggestions and comments are welcome, please send me an email (see contacts).