-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpascal.java
More file actions
39 lines (36 loc) · 1.09 KB
/
pascal.java
File metadata and controls
39 lines (36 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class pascal {
public static void main(String[] args) {
try{
pascalTriangle(5, 5);}
catch(Exception e){System.out.println(e);}
}
public static int[] pascalTriangle(int n, int size)throws Exception{
if(size<n){
throw new IllegalArgumentException("Triangle size is smaller than rows ");
}
if(n == 0){
int[] r = {1,0};
printRow(r, n, size, 4);
return r;
}
else {
int[] r = pascalTriangle(n-1, size);
int[] temp = new int[n+2];
temp[0] = 1;
for(int i= 0; i < r.length-1;i++){
temp[i+1] = r[i] + r[i+1];
}
printRow(temp, n, size, 4);
return temp;
}
}
static void printRow(int[] row, int n, int size, int cellWidth) {
// leading indent in cells
System.out.print(" ".repeat((size - n) * (cellWidth / 2)));
// print values
for (int i = 0; i < row.length - 1; i++) {
System.out.printf("%" + cellWidth + "d", row[i]);
}
System.out.println();
}
}