/* three.cpp: three ways to build MultiMatrix on top of Array
 *
 *   -DKIND=1   a field with pointers to the smaller matrices (the book)
 *   -DKIND=2   inherited from the array of pointers
 *   -DKIND=3   a field with the smaller matrices themselves ("live")
 *   -DGROW     adds one assignment that makes the top level grow
 *   -DTIME     runs the time test instead of the allocation test
 *
 *   g++ -Wall -Wextra -ansi -pedantic -DKIND=1 three.cpp -o three
 *   valgrind ./three 2>&1 | grep 'heap usage'
 *
 *   g++ -Wall -Wextra -ansi -pedantic -O2 -DKIND=1 -DTIME three.cpp -o three
 *   ./three
 */
#include <stdio.h>
#include <time.h>

#ifndef KIND
#define KIND 1
#endif

template <class T>
class Array {
    T *p;
    T init;
    unsigned int size;
public:
    Array(const T& in) : p(0), init(in), size(0) {}
    ~Array() { delete[] p; }
    T& operator[](unsigned int idx) {
        if (idx >= size)
            Resize(idx);
        return p[idx];
    }
    const T& operator[](unsigned int idx) const {
        return idx >= size ? init : p[idx];
    }
    unsigned int Size() const { return size; }
#if KIND == 3                           /* live: copying must really work */
    Array(const Array<T>& other) : p(0), init(other.init), size(0)
        { *this = other; }
    Array<T>& operator=(const Array<T>& other) {
        if (this == &other)
            return *this;
        T *copy = other.size ? new T[other.size] : 0;
        for (unsigned int i = 0; i < other.size; i++)
            copy[i] = other.p[i];
        delete[] p;
        p = copy;
        init = other.init;
        size = other.size;
        return *this;
    }
#endif
private:
    void Resize(unsigned int required_index) {
        unsigned int new_size = size == 0 ? 8 : size;
        while (new_size <= required_index)
            new_size *= 2;
        T *new_array = new T[new_size];
        for (unsigned int i = 0; i < new_size; i++)
            new_array[i] = i < size ? p[i] : init;
        delete[] p;
        p = new_array;
        size = new_size;
    }
#if KIND != 3                           /* pointers: copying stays forbidden */
    void operator=(const Array<T>&) {}
    Array(const Array<T>&) {}
#endif
};

#if KIND == 1           /* ---- a field with pointers (the book) ---- */

template <class T, T init_val, int dim>
class MultiMatrix {
    typedef MultiMatrix<T, init_val, dim-1> Sub;
    Array<Sub*> arr;
public:
    MultiMatrix() : arr(0) {}
    ~MultiMatrix() {
        for (unsigned int i = 0; i < arr.Size(); i++)
            delete arr[i];
    }
    Sub& operator[](unsigned int idx) {
        if (!arr[idx])
            arr[idx] = new Sub;
        return *arr[idx];
    }
    const Sub& operator[](unsigned int idx) const {
        static Sub dummy;
        return arr[idx] ? *arr[idx] : dummy;
    }
};

#elif KIND == 2         /* ---- inherited from the array of pointers ---- */

template <class T, T init_val, int dim>
class MultiMatrix : public Array<MultiMatrix<T, init_val, dim-1>*> {
    typedef MultiMatrix<T, init_val, dim-1> Sub;
    typedef Array<Sub*> Base;
public:
    MultiMatrix() : Base(0) {}
    ~MultiMatrix() {
        for (unsigned int i = 0; i < Base::Size(); i++)
            delete Base::operator[](i);
    }
    Sub& operator[](unsigned int idx) {
        if (!Base::operator[](idx))
            Base::operator[](idx) = new Sub;
        return *Base::operator[](idx);
    }
    const Sub& operator[](unsigned int idx) const {
        static Sub dummy;
        return Base::operator[](idx) ? *Base::operator[](idx) : dummy;
    }
};

#else                   /* ---- a field with the matrices themselves ---- */

template <class T, T init_val, int dim>
class MultiMatrix {
    typedef MultiMatrix<T, init_val, dim-1> Sub;
    Array<Sub> arr;
public:
    MultiMatrix() : arr(Sub()) {}
    Sub& operator[](unsigned int idx) { return arr[idx]; }
    const Sub& operator[](unsigned int idx) const { return arr[idx]; }
};

#endif

template <class T, T init_val>
class MultiMatrix<T, init_val, 1> : public Array<T> {
public:
    MultiMatrix() : Array<T>(init_val) {}
};

/* count the allocations of this one with valgrind, with and without GROW */
void alloc_test()
{
    MultiMatrix<int, -1, 3> m;
    const MultiMatrix<int, -1, 3>& c = m;

    for (int j = 0; j < 1000; j++)
        m[0][j][0] = j;                 /* 1000 rows inside m[0] */
#ifdef GROW
    m[8][0][0] = 5;                     /* the top level grows: 8 -> 16 */
#endif
    printf("%d %d %d %d\n", c[0][0][0], c[0][999][0], c[8][0][0],
           c[3][3][3]);
}

/* ten growths of the top level, with side x side ints stored below it */
void time_test(int side)
{
    MultiMatrix<int, -1, 3> m;
    clock_t start, mid, end;

    start = clock();
    for (int j = 0; j < side; j++)
        for (int k = 0; k < side; k++)
            m[0][j][k] = j + k;
    mid = clock();
    for (int i = 8; i <= 4096; i *= 2)
        m[i][0][0] = i;                 /* 8 -> 16 -> ... -> 8192 slots */
    end = clock();
    printf("fill %d x %d: %.1f ms\n", side, side,
           (mid - start) * 1000.0 / CLOCKS_PER_SEC);
    printf("ten growths:      %.1f ms\n",
           (end - mid) * 1000.0 / CLOCKS_PER_SEC);
}

int main()
{
#ifdef TIME
    time_test(2000);
#else
    alloc_test();
#endif
    return 0;
}
