`

自己写的杨辉三角

 
阅读更多
package com.lee.graphic;

public class YangHuiTriangle {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int row = 10;
		int colunm = row * 2;
		int half_colunm = colunm / 2;
		
		int [][]array = new int [row][colunm];
		
		int index = 0;
		for(int i = 0; i < row; i++){
			//左边三角形
			for(int j = 0; j < half_colunm - i - 1; j++){
				array[i][j] = 0; 
				index++;
			}
			//为单独的1赋值
			array[i][index++] = 1;
			//从第2行起,规律为里边的任意一个数等于上一行的左上+右上
			if(i != 0){
				//内部三角形
				for(int k = 0; k < i * 2; k++){
					if(k % 2 == 0){
						array[i][index] = 0;
					}else{
						array[i][index] = array[i - 1][index - 1] + array[i - 1][index + 1];
					}
					index++;
				}
				//计算剩余的行
				int lastColunm = row - index;
				for(int j = 0; j < lastColunm; j++){
					array[i][index] = 0; 
					index++;
				}
			}
			//每一行重置指针index
			index = 0;
			
		}
		//格式输出
		for(int i = 0; i < row; i++){
			for(int j = 0; j < colunm; j++){  
				if(array[i][j] == 0){
					System.out.printf("%-3s",""); 
				}else{
	                System.out.printf("%-3s",array[i][j]); 
				}
			}
			System.out.println();
		}
		
	}

}



[img]
http://dl.iteye.com/upload/attachment/0072/1974/2f64110c-a0ba-39cb-a533-600a9e8832eb.jpg
[/img]

写完之后,发现有多处可以改进的地方,不过功能实现了,有需求再改进吧
  • 大小: 24 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics