Skip to content

Commit 5855983

Browse files
authored
Add Trinomial triangle TheAlgorithms#2651 (TheAlgorithms#2652)
1 parent 831a0a4 commit 5855983

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Maths/TrinomialTriangle.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package Maths;
2+
3+
/**
4+
* The trinomial triangle is a variation of Pascal’s triangle. The difference
5+
* between the two is that an entry in the trinomial triangle is the sum of the
6+
* three (rather than the two in Pasacal’s triangle) entries above it
7+
*
8+
* Example Input: n = 4
9+
* Output
10+
* 1
11+
* 1 1 1
12+
* 1 2 3 2 1
13+
* 1 3 6 7 6 3 1
14+
*/
15+
public class TrinomialTriangle {
16+
17+
public static int TrinomialValue(int n, int k) {
18+
if (n == 0 && k == 0) {
19+
return 1;
20+
}
21+
22+
if (k < -n || k > n) {
23+
return 0;
24+
}
25+
26+
return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1);
27+
}
28+
29+
public static void printTrinomial(int n) {
30+
for (int i = 0; i < n; i++) {
31+
for (int j = -i; j <= 0; j++) {
32+
System.out.print(TrinomialValue(i, j) + " ");
33+
}
34+
35+
for (int j = 1; j <= i; j++) {
36+
System.out.print(TrinomialValue(i, j) + " ");
37+
}
38+
39+
System.out.println();
40+
}
41+
}
42+
43+
public static void main(String argc[]) {
44+
int n = 6;
45+
printTrinomial(n);
46+
}
47+
}

0 commit comments

Comments
 (0)