// Arup Guha
// 6/8/2020
// Code for Solution to E1-DMA portion of the first COP 3502 Exam (Summer 2020)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int* getNextRow(int* curRow, int length);
void print(int* arr, int len);

int main(void) {

    // Test Code for Question #1
    int* arr = malloc(sizeof(int));
    arr[0] = 1;
    print(arr, 1);
    for (int i=1; i<=10; i++) {
        arr = getNextRow(arr, i);
        print(arr, i+1);
    }
    free(arr);

    // Code segment for question 2.
    int res = 0;
    int n;
    scanf("%d", &n);
    int* sizes = malloc(n*sizeof(int));
    char** words = malloc(n*sizeof(char*));

    // Add in bytes here.
    res += (4*n + 4*n);

    for (int i=0; i<n; i++) {
        char temp[100];
        scanf("%s", temp);
        sizes[i] = strlen(temp)+1;
        words[i] = malloc(sizes[i]*sizeof(char));
        strcpy(words[i], temp);

        // And these bytes.
        res += (sizes[i]);
    }

    printf("%d bytes dynamically allocated.\n", res);

    // free code here.
    for (int i=0; i<n; i++)
        free(words[i]);
    free(words);
    free(sizes);

    return 0;
}

// Pre-condition: curRow is an array of size length, length is 1 or greater, and curRow stores
//                the row of Pascal's Triangle of length length.
// Post-condition: The next row of Pascal's Triangle is calculated, the memory for curRow is freed
//                 and a pointer to the array storing the next row is returned.
int* getNextRow(int* curRow, int length) {

    // Allocate the array.
    int* res = malloc((length+1)*sizeof(int));

    // Put 1s at front and end.
    res[0] = 1;
    res[length] = 1;

    // Use the addition formula to put in each middle term.
    for (int i=0; i<length-1; i++)
        res[i+1] = curRow[i] + curRow[i+1];

    // Free the memory.
    free(curRow);

    // Return the pointer to the new array.
    return res;
}

// Just for testing.
void print(int* arr, int len) {
    for (int i=0; i<len; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
