달력

5

« 2024/5 »

  • 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
2011. 6. 18. 18:17

[java] Pascal Triangle by array 용-ILE/LANG-JAVA(JSP)2011. 6. 18. 18:17


fs 2011.06

파스칼 삼각형 상위값 합이 자기 값인거!! 자바 배열로 출력

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

/**
 * <pre>
  * FileName  : pascalTriangle.java
  * Package   :
  * Comment   :
  * </pre>
  *
  * @author   : http://suite.tistory.com/
  * @date     : 2011. 6. 18.
 */
public class pascalTriangle {

 public static void main(String[] args) {
  int HEIGHT = 100;
  final int CNUM = 1;
  long[][] dataArray = new long[HEIGHT][];
  for (int i = 0; i < HEIGHT; i++) {
   int cnt = 0;
   dataArray[i] = new long[i + 1];
   for (int j = 0; j < i + 1; j++) {
    if (cnt == 0 || i == j) {
     dataArray[i][cnt++] = CNUM;
     continue;
    } else {
     long val = dataArray[i - 1][j] + dataArray[i - 1][j - 1]; // 바로 상위 두개 값 합
     dataArray[i][cnt++] = val;

    }
   }
  }
  // print
  for (int k = 0; k < HEIGHT; k++) {
   for (int idx = 0; idx < dataArray[k].length; idx++) {
    System.out.print(dataArray[k][idx] + " ");
   }
   System.out.println();
  }
 }
}


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
결과

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
......
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 

:
Posted by mastar