#include #include #include "pascal.h" /* default size for a triangle */ #define INITIAL_SIZE 5 struct triangle { int limite; long **cases; }; static void line_fill(triangle tr, int i) { int j; tr->cases[i][0] = 1; tr->cases[i][i] = 1; for (j = 1; j < i; j++) tr->cases[i][j] = tr->cases[i - 1][j - 1] + tr->cases[i - 1][j]; } static void extension(triangle tr, int new_limit) { /* we suppose that we REALLY do extend it */ int i; int new_size = new_limit + 1; int old_limit = tr->limite; long ** new_cases = realloc(tr->cases, new_size * sizeof(long *)); tr->limite = new_limit; tr->cases = new_cases; for (i = old_limit + 1; i < new_size; i++) { new_cases[i] = malloc((i + 1) * sizeof(long)); line_fill(tr, i); } } triangle triangle_allocate(void) { long ** cases = malloc ((INITIAL_SIZE + 1) * sizeof(long *)); triangle tr = malloc(sizeof (struct triangle)); int i; for (i=0; i <= INITIAL_SIZE; i++) cases[i] = malloc((i + 1) * sizeof(long)); tr->limite = INITIAL_SIZE; tr->cases = cases; return tr; } void triangle_free(triangle tr) { int i; for (i = 0; i <= tr->limite; i++) free(tr->cases[i]); free(tr); } void triangle_display(triangle tr) { int i; int j; for (i = 0; i <= tr->limite; i++) { for (j = 0; j <= i; j++) printf("%d ",tr->cases[i][j]); printf("\n"); } } void triangle_fill(triangle tr) { int i; int j; tr->cases[0][0]=1; for (i = 1; i <= tr->limite; i++) line_fill(tr,i); } int triangle_check(triangle tr) { int i; int j; long puis2 = 1; for (i = 1; i < tr->limite; i++) { long somme = 0; for (j = 0; j <= i; j++) somme += tr->cases[i][j]; if (somme != 2*puis2) return 0; puis2 = somme; } return 1; } long binomial(triangle tr, int i, int j) { if (j < 0 || j > i) return 0; else if (i > tr->limite ) extension(tr,i); return tr->cases[i][j]; }