package main; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; class PyramidCalculator { private final File file; private final ArrayList numList; private final ArrayList intNumList; private final int ROW_NUMBER; public PyramidCalculator(File file) throws IOException { this.file = file; this.numList = extractFromFile(); this.ROW_NUMBER = numList.size() - 1; this.intNumList = convertToInt(); } public ArrayList extractFromFile() throws FileNotFoundException { ArrayList tempList = new ArrayList<>(); Scanner reader = new Scanner(this.file); while (reader.hasNext()) { String line = reader.nextLine(); tempList.add(line.split(" ")); } return tempList; } public ArrayList convertToInt() { ArrayList tempList = new ArrayList<>(); for(String[] line: this.numList) { int[] tempArray = new int[line.length]; for (int i = 0; i < line.length; i++) { tempArray[i] = Integer.parseInt(line[i]); } tempList.add(tempArray); } return tempList; } public static boolean isPrime(int num) { if (num == 1 || num == 2) { return false; } else { for (int i = 2; i < num; i++) { if (num % i == 0) { return false; } } } return true; } public void maxSum() { ArrayList pyramid = this.intNumList; int row = this.ROW_NUMBER; for (int i = row - 1; i > -1; i--) { for (int j = 0; j < i + 1; j++) { int temp1 = pyramid.get(i + 1)[j]; int temp2 = pyramid.get(i + 1)[j + 1]; if (isPrime(pyramid.get(i)[j])) { pyramid.get(i)[j] = -1; } if (i == row - 1) { if (pyramid.get(i)[j] != -1) { if (isPrime(temp1) && !isPrime(temp2)) { pyramid.get(i)[j] += temp2; } else if (isPrime(temp2) && !isPrime(temp1)) { pyramid.get(i)[j] += temp1; } else if (isPrime(temp1) && isPrime(temp2)){ pyramid.get(i)[j] = -1; } } } else { if (pyramid.get(i)[j] != -1) { pyramid.get(i)[j] += Math.max(temp1, temp2); } } } } System.out.println(pyramid.get(0)[0]); } } public class Main { public static void main(String[] args) { File file = new File("assignment.txt"); try { PyramidCalculator pc = new PyramidCalculator(file); pc.maxSum(); } catch (IOException e) { e.getStackTrace(); } } }