This algorithm is very slow but it will calculate well up to row 10-15 lol, and it's a little harder to make mistakes with recursion. A recursive solution is a stupid solution to this problem, I was just curious if I could do it elegantly with recursion, not so sure it's possible
It will compute the nth row in pascals triangle.
To get the 6th row run it like this: java Pascal 6
NB: I called the first row: row 1 and not row 0
If you need to print the whole triangle that shouldn't be too hard of a modification
Code
import java.util.*;
public class Pascal {
static Integer[] triangle;
public static void main(String[] args) {
String rowsString = args[0];
int rows = Integer.parseInt(rowsString);
triangle = pascalsTriangle(rows);
for(Integer i: triangle){
System.out.print(i + " ");
}
}
public static Integer[] pascalsTriangle(int rows) {
if(rows == 1)
return new Integer[]{1};
else if(rows == 2)
return new Integer[]{1,1};
else if(rows == 3)
return new Integer[]{1,2,1};
else{
//row represents a row in the triangle
Integer[] row = new Integer[rows];
//we know the begining and end of the row will be 1
row[0] = 1;
row[rows-1] = 1;
for(int i=1; i<rows-1; i++){
row[i] = pascalsTriangle(rows-1)[i-1] + pascalsTriangle(rows-1)[i];
}
return row;
}
}
}
This post was edited by zeroRooter on Sep 12 2015 12:59pm