blaenk (owner)

Revisions

gist: 121912 Download_button fork
public
Description:
Shows any given row from Pascal's Triangle
Public Clone URL: git://gist.github.com/121912.git
Embed All Files: show embed
Java #
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import java.util.Scanner;
 
public class PascalsTriangle
{
   public static int[] calculateNumbers(int row)
   {
      // create a temporary integer array to hold the
      // integer values of the current row
      // its size is equal to the row number
      int[] temp = new int[row];
      
      // this is going to be set by the recursive call
      // to this function and will contain the numbers
      // of the row before this current row
      int[] rev;
 
      // if it's the first row, then it only consists of one number (1)
      // so just set the array element to 1
      if (row == 1)
         temp[0] = 1;
         
      else
      {
         // get the row numbers for the previous row
         // by recursively calling this function
         rev = calculateNumbers(row - 1);
 
         // the first number is always 1
         temp[0] = 1;
 
         // the number is always equal to the sum of the number at
         // this number's position - 1 and the number at same position
         // as this number. we stop two numbers before because we are
         // not counting the first and last '1'. We start with '1'
         // because temp[0] contains the first 0
         for (int i = 1; i <= row - 2; i++)
            temp[i] = rev[i - 1] + rev[i];
 
         // the last number is always 1
         temp[row - 1] = 1;
      }
      
      // return the array of that row's values
      return temp;
   }
 
   public static void main(String[] args)
   {
      Scanner scan = new Scanner(System.in);
      int[] numbers; // to hold the list numbers on the specified row
      int row; // to hold the specified row number
 
      System.out.println("What row should I display?");
      row = scan.nextInt();
      
      // get the row numbers
      numbers = calculateNumbers(row);
 
      // output the row numbers
      for (int i = 0; i < row; i++)
         System.out.print(numbers[i] + "\t");
 
      System.out.println();
    }
}