Posting interesting threads in computer programming, technologies, science, etc.
Tuesday, April 24, 2012
Fun creating the pascal triangle using java
The simplest way to approach this problem is by using the knowledge of multidimensional arrays. So how do we start? First of all we identify this as a two-dimensional array. If you are unfamiliar with two dimensional array, the syntax goes like this: <type of array><name> = new <type of array><size of array>. For example, an one dimensional integer array name "numbers" that is of size 5 will have the syntax of the following: int[]numbers = new int[5].
Coming back to our problem, a two dimensional array is very similar to its one dimension counterpart. For instance, a 2x2 integer arrays would have a syntax of the following: int [][] name = new int[2][2]. Since the shape of the pascal triangle is jagged, the syntax will start in some form like the following: int[] [] triangle = new int[7][ ].
Now the most important part to solve this problem is to recognize the pattern. Notice that there are one number in the first row, two numbers in second, three in the third, and so on. Since array uses zero-based index, meaning that 0=1, 1=2,2=3, etc. Another trick to recognize is that it always start and end with '1'. The last thing to notice is that the middle elements are made by adding numbers directly above and one to the left on the previous line. After finishing analyzing the problem, it's time to put it to Java form.
The code will look like the following:
public class PascalTriangle{
public static void main(String[] args){
int[ ][ ] triangle = new int[7][ ];//because it's jagged.
makeTriangle(triangle);//the method that form the pascal triangle.
display(triangle);//print the triangle on console.
}
public static void makeTriangle(int[ ][ ] triangle){
for(int i = 0;i<triangle.length;i++){
triangle[i] = new int[i+1]; //each line has one more element.
triangle[i][0] = 1; //first number on each line always '1'
triangle[i][i] = 1; // last number on each line always '1'
for(int j = 1;j< i; j++){
triangle[i][j] = triangle[i-1][j]+triangle[i-1][j-1];
}
}
}
public static void print(int[ ][ ] triangle){
for(int i=0; i< triangle.length; i++){
for(int j=0; j<triangle[i].length; j++){
System.out.print(triangle[i][j]+" ");
}
System.out.println();
}
}
}
Sorry about any unclear parts in this tutorial, as I am still quite new to the blogging community. Please feel free to leave comments on how I can improve my blog. Thanks!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment