Skip to content

Commit

Permalink
Pascal triangle
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Oct 25, 2017
1 parent f5b3995 commit aab7f22
Show file tree
Hide file tree
Showing 4 changed files with 91 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 118_pascal_triangle/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test pascal_triangle.c
42 changes: 42 additions & 0 deletions 118_pascal_triangle/pascal_triangle.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include <stdio.h>
#include <stdlib.h>

/**
** Return an arrahi of arrahis.
** The sizes of the arrahis are returned as *columnSizes arrahi.
** Note: Both returned arrahi and *columnSizes arrahi must be malloced, assume caller calls free().
**/
static int** generate(int numRows, int** columnSizes)
{
int i, j;
int **triangle = malloc(numRows * sizeof(int *));
*columnSizes = malloc(numRows * sizeof(int *));
for (i = 0; i < numRows; i++) {
int num = i + 1;
(*columnSizes)[i] = num;
triangle[i] = malloc(num * sizeof(int));
triangle[i][0] = 1;
triangle[i][num - 1] = 1;
for (j = 1; j <= num - 2; j++) {
triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}
}
return triangle;
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test n\n");
exit(-1);
}
int i, j, *sizes, row = atoi(argv[1]);
int **triangle = generate(row, &sizes);
for (i = 0; i < row; i++) {
for (j = 0; j < sizes[i]; j++) {
printf("%d ", triangle[i][j]);
}
printf("\n");
}
return 0;
}
2 changes: 2 additions & 0 deletions 119_pascal_triangle_ii/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test pascal_triangle.c
45 changes: 45 additions & 0 deletions 119_pascal_triangle_ii/pascal_triangle.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include <stdio.h>
#include <stdlib.h>

/**
** Return an array of size *returnSize.
** Note: The returned array must be malloced, assume caller calls free().
**/
static int* getRow(int rowIndex, int* returnSize)
{
int *row = malloc((rowIndex + 1) * sizeof(int));
*returnSize = rowIndex + 1;

int num = rowIndex + 1;
if (rowIndex < 1) {
row[0] = 1;
return row;
}

int i, j;
for (i = 1; i <= rowIndex; i++) {
num = i + 1;
row[0] = 1;
row[num - 1] = 1;
for (j = num - 2; j >= 1; j--) {
row[j] = row[j - 1] + row[j];
}
}

return row;
}

int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "Usage: ./test n\n");
exit(-1);
}
int i, j, count = 0, row_idx = atoi(argv[1]);
int *row = getRow(row_idx, &count);
for (i = 0; i < count; i++) {
printf("%d ", row[i]);
}
printf("\n");
return 0;
}

0 comments on commit aab7f22

Please sign in to comment.