// Arup Guha
// 1/24/2024
// Solution to COP 3502H Exam 1 Question 4

#include <stdio.h>
#include <stdlib.h>

int** powerarray(int n);

int main() {

    // Small test.
    int** v = powerarray(5);

    // Check it.
    for (int i=0; i<=5; i++) {
        for (int j=0; j<(1<<i); j++)
            printf("%3d", v[i][j]);
        printf("\n");
    }

    // Free stuff.
    for (int i=0; i<=5; i++) free(v[i]);
    free(v);

    return 0;
}

int** powerarray(int n) {

    // n+1 pointers.
    int** res = calloc(n+1, sizeof(int*));

    // Calculate 2 to the n.
    int skip = 1;
    for (int i=0; i<n; i++)
        skip *= 2;

    // i is which row we are on, size is the # of elements on that row.
    for (int i=0,size=1; i<=n; i++,size*=2) {

        // So we allocate size slots. Because we calloc, 0 is in index 0.
        res[i] = calloc(size, sizeof(int));

        // Just add skip to the previous.
        for (int j=1; j<size; j++)
            res[i][j] = res[i][j-1] + skip;

        // Update skip for next row.
        skip /=2;
    }

    // Ta da!
    return res;
}
