import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Scanner; public class FindMaxSum { public static final int ROW = 15; public static final int COLUMN = 15; public static int[][] numArray = new int[ROW][COLUMN]; /* * Checks the numbers whether is prime or not */ private static boolean isPrime(int n) { for (int i = 2; i < n; ++i) { if ((n % i) == 0) { return false; } } return true; } public static int findMaximum(String file, ArrayList path) { readFile(file, numArray); if (isPrime(numArray[0][0])) { return 0; } else { return maxSummation(0, 0, ROW, path); } } private static void readFile(String file, int[][] data) { try { InputStream inputStream = new FileInputStream(file); Scanner sc = new Scanner(inputStream); int count = 0; while (sc.hasNextLine()) { String line = sc.nextLine(); String[] numbers = line.split("\\s+"); for (int i = 0; i < numbers.length; ++i) { data[count][i] = Integer.parseInt(numbers[i]); } ++count; } } catch (FileNotFoundException e) { System.out.println("File cannot be found!"); java.lang.System.exit(1); }catch (IOException e){ System.out.println("There is a problem in input or output!"); java.lang.System.exit(1); } catch (ArrayIndexOutOfBoundsException e){ System.out.println("Row or colum sizes are wrong!"); java.lang.System.exit(1); } } private static int maxSummation(int x, int y, int lenght, ArrayList path) { int totalLeft = 0 ; int totalRight = 0; ArrayList right = new ArrayList<>(); ArrayList left = new ArrayList<>(); if (x >= lenght) { return 0; } else if (x == (lenght - 1)) { path.add(new Location(x, y, numArray[x][y])); return numArray[x][y]; } if (!isPrime(numArray[x + 1][y])) { totalRight = maxSummation(x + 1, y, lenght, right); } if (!isPrime(numArray[x + 1][y + 1])) { totalLeft = maxSummation(x + 1, y + 1, lenght, left); } if (isPrime(numArray[x + 1][y + 1]) && isPrime(numArray[x + 1][y])) return Integer.MIN_VALUE; if (totalLeft > totalRight) { path.addAll(left); path.add(new Location(x, y, numArray[x][y])); return totalLeft + numArray[x][y]; } else { path.addAll(right); path.add(new Location(x, y, numArray[x][y])); return totalRight + numArray[x][y]; } } private static class Location { private int x; // x private int y; // y private int value; // value public Location(int x, int y, int value) { this.x = x; this.y = y; this.value = value; } public int getX() { return x; } public int getY() { return y; } public int getValue() { return value; } } public static void main(String args[]) { ArrayList path = new ArrayList<>(); System.out.printf("\nThe Result: \n\n%d", findMaximum("C:\\Users\\Sena Celebi\\Desktop\\data.txt", path)); } }