I want to maximum sum in a triangle(pyramid) but non-prime numbers must be collected This is my code :
private static int[][] arrlist;
private static ArrayList list = new ArrayList();
public static void main(String[] args) throws Exception {
int[][] data = Files.lines(Paths.get("D:\\new.txt"))
.map(s -> stream(s.trim().split("\\s+"))
.mapToInt(Integer::parseInt)
.toArray())
.toArray(int[][]::new);
arrlist=data;
int sum=0;
func(0,0,sum);
int max= (int)Collections.max(list);
System.out.println("list"+list);
System.out.println("max-" + max);
}
private static void func(int x, int y, int sum) {
//stop status
if ((isPrime(arrlist[x + 1][y])) && (isPrime(arrlist[x + 1][y + 1])) || x == 13)
{
list.add(sum);
return;
}
func(x + 1, y, sum + arrlist[x + 1][y]);
func(x + 1, y + 1, sum + arrlist[x + 1][y+1]);
}
public static boolean isPrime(int num) {
for (int i = 2; i < num; i++) {
if (num % i == 0)
return false;
}
return true;
}
and this is my new.txt : (only allowed to walk downwards and diagonally and only over non prime numbers)
215
193 124
117 237 442
218 935 347 235
320 804 522 417 345
229 601 723 835 133 124
248 202 277 433 207 263 257
359 464 504 528 516 716 871 182
461 441 426 656 863 560 380 171 923
381 348 573 533 447 632 387 176 975 449
223 711 445 645 245 543 931 532 937 541 444
330 131 333 928 377 733 017 778 839 168 197 197
131 171 522 137 217 224 291 413 528 520 227 229 928
223 626 034 683 839 53 627 310 713 116 629 817 410 121
924 622 911 233 325 139 721 218 253 223 528 233 230 124 233
this code output : 8128 but not correct. Correct answer :8186
Where can I make mistakes ? Help me,please..
Try this.
private static int func(int x, int y) {
if (x >= arrlist.length)
return 0;
int self = arrlist[x][y];
if (isPrime(self))
return 0;
else
return self + Math.max(func(x + 1, y), func(x + 1, y + 1));
}
and
System.out.println("max-" + func(0, 0)); // -> max-8186