package assessment; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.ArrayList; import java.util.Scanner; class FindMaximumPathSumOfTriangle { public static final int ROW = 15; public static final int COLUMN = 15; public static int[][] newArray = new int[ROW][COLUMN]; public static int findMaxSum(String fileName, ArrayList path) throws FileNotFoundException { readNumbersFromFile(fileName, newArray); if (checkPrime(newArray[0][0])) { return 0; } else { return findMaxSumRec(0, 0, ROW, path); } } private static int findMaxSumRec(int x, int y, int size, ArrayList path) { int totalLeft = 0; int totalRight = 0; ArrayList tempListLeft = new ArrayList<>(); ArrayList tempListRight = new ArrayList<>(); if (x >= size) { return 0; } else if (x == (size - 1)) { path.add(new Coodinates(x, y, newArray[x][y])); return newArray[x][y]; } if (!checkPrime(newArray[x + 1][y])) { totalRight = findMaxSumRec(x + 1, y, size, tempListRight); } if (!checkPrime(newArray[x + 1][y + 1])) { totalLeft = findMaxSumRec(x + 1, y + 1, size, tempListLeft); } if (checkPrime(newArray[x + 1][y + 1]) && checkPrime(newArray[x + 1][y])) return Integer.MIN_VALUE; if (totalLeft > totalRight) { path.addAll(tempListLeft); path.add(new Coodinates(x, y, newArray[x][y])); return totalLeft + newArray[x][y]; } else { path.addAll(tempListRight); path.add(new Coodinates(x, y, newArray[x][y])); return totalRight + newArray[x][y]; } } private static boolean checkPrime(int number) { for (int i = 2; i < number; ++i) { if ((number % i) == 0) { return false; } } return true; } private static void readNumbersFromFile(String fileName, int[][] numbersArray) throws FileNotFoundException { InputStream inputStream = new FileInputStream(fileName); Scanner scanner = new Scanner(inputStream); int index = 0; while (scanner.hasNextLine()) { String line = scanner.nextLine(); String[] numbers = line.split("\\s+"); for (int i = 0; i < numbers.length; ++i) { numbersArray[index][i] = Integer.parseInt(numbers[i]); } ++index; } } private static class Coodinates { private int x; // x coordinate of number private int y; // y coordinate of number private int number; // number public Coodinates(int x, int y, int number) { this.x = x; this.y = y; this.number = number; } } public static void main(String args[]) throws FileNotFoundException { ArrayList path = new ArrayList<>(); System.out.printf("Maximum Path Sum is %d", findMaxSum("C:\\Users\\Dell\\Desktop\\JAVA\\oop\\src\\assessment\\text.txt", path)); } }