Algorithm Gossip巴斯卡(Pascal)

570阅读 0评论2009-11-26 dongyue91
分类:

巴斯卡(Pascal)三角形基本上就是在解 nCr ,因為三角形上的每一個數字各對應一個nCr,其中 n 為 row,而 r 為 column,如下:
    0C0
   1C0 1C1
  2C0 2C1 2C2
 3C0 3C1 3C2 3C3
4C0 4C1 4C2 4C3 4C4

對應的數據如下圖所示: 

PHP:

<?php
function abc($n)
{
    //计算 存入数组
    for($i=1;$i<=$n;$i++)
    {
        for($j=0;$j<$i;$j++)
        {
            if($j == 0)
            {
                $temp[$i][$j] = 1;
            }
            else
            {
                $temp[$i][$j] = $temp[$i-1][$j-1] + $temp[$i-1][$j];
            }
        }
    }
    
    //显示
    $space = ' ';
    $con_out = count($temp);
    for($i=0;$i<=$con_out;$i++)
    {
        $con_in = count($temp[$i]);
        for($j=0;$j<$con_in;$j++)
        {
            if($j == 0)
            {
                echo str_repeat($space,($n-$i));
            }
            echo $temp[$i][$j].$space;
        }
        echo '
'
;
    }
}

abc(13);
?>


Python:

def abc(n):
    //Python的初始化二维数组,真是头疼
    temp = [[0 for col in range(n)] for row in range(n)]
    for i in range(1, n):
        for j in range(0, i):
            if j==0:
                temp[i][j] = 1
            else:
                temp[i][j] = temp[i-1][j-1] + temp[i-1][j]
    for i in range(0, n):
        for j in range(0, i):
            print(temp[i][j], end=" ")
        print('\n');


C:

/*
  Name: 巴斯卡
  Copyright: 1.0
  Author: Mervin.G
  Date: 2009-11-26
  Description: 输出N行后的数字
*/


#include <stdio.h>
#include <conio.h>
#include <windows.h>

void sjx(int n)
{
    int i;
    int j;
    int temp[n][n];
    
    //初始化整个数组值为0
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            temp[i][j] = 0;
        }
    }
    
    for(i=0;i<n;i++)
    {
        for(j=0;j<i;j++)
        {
            if(j == 0)
            {
                temp[i][j] = 1;
            }
            else
            {
                if(j > 0 && i > 0)
                {
                    temp[i][j] = temp[i-1][j-1] + temp[i-1][j];
                }
                else
                {
                    temp[i][j] = temp[i][j] + 0;
                }
            }
        }
    }
    for(i=0;i<n;i++)
    {
        for(j=0;j<i;j++)
        {
            printf("%d ",temp[i][j]);
        }
        printf("\n");
    }
}

main()
{
    int igetch;
    sjx(14);
    
    //监听用户键盘操作,直到ESC时退出
    while (true)
    {
        igetch = getch();
        if(igetch == 27)
        {
            exit(0);
        }
        else
        {
            printf("%d\n",igetch);
        }
    }
}


上一篇:Windows下的Memcache安装
下一篇:LINUX下安装并配置JAVA,eclipse环境