
#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include "linalg.h"


int main(int argc, char** argv)
{
    //
    // This example demonstrates creation/initialization of the sparse matrix
    // and matrix-vector multiplication.
    //
    // First, we have to create matrix and initialize it. Matrix is initially created
    // in the Hash-Table format, which allows convenient initialization. We can modify
    // Hash-Table matrix with sparseset() and sparseadd() functions.
    //
    // NOTE: Unlike CRS format, Hash-Table representation allows you to initialize
    // elements in the arbitrary order. You may see that we initialize a[0][0] first,
    // then move to the second row, and then move back to the first row.
    //

    double v;
    alglib::sparsematrix s;
    alglib::sparsecreate(2, 2, s);
    alglib::sparseset(s, 0, 0, 2.0);
    alglib::sparseset(s, 1, 1, 1.0);
    alglib::sparseset(s, 0, 1, 1.0);

    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0;j < 2; j++) {
            v = sparseget(s, i,j);
            printf("%.1f   ", v);
        }
        printf("\n");
    }


    alglib::sparseadd(s, 1, 1, 4.0);

    

    printf("\n ==================================\n\n");

    for (i = 0; i < 2; i++) {
        for (j = 0;j < 2; j++) {
            v = sparseget(s,i,j );
            printf("%.1f   ", v);
        }
        printf("\n");
    }
    printf("\n ==================================\n\n");
    // Now S is equal to
    //   [ 2 1 ]
    //   [   5 ]
    // Lets check it by reading matrix contents with sparseget().
    // You may see that with sparseget() you may read both non-zero
    // and zero elements.
    //

    v = sparseget(s, 0, 0);
    printf("%.2f\n", double(v)); // EXPECTED: 2.0000
    v = sparseget(s, 0, 1);
    printf("%.2f\n", double(v)); // EXPECTED: 1.0000
    v = sparseget(s, 1, 0);
    printf("%.2f\n", double(v)); // EXPECTED: 0.0000
    v = sparseget(s, 1, 1);
    printf("%.2f\n", double(v)); // EXPECTED: 5.0000

    //
    // After successful creation we can use our matrix for linear operations.
    //
    // However, there is one more thing we MUST do before using S in linear
    // operations: we have to convert it from HashTable representation (used for
    // initialization and dynamic operations) to CRS format with sparseconverttocrs()
    // call. If you omit this call, ALGLIB will generate exception on the first
    // attempt to use S in linear operations. 
    //
    alglib::sparseconverttocrs(s);

    //
    // Now S is in the CRS format and we are ready to do linear operations.
    // Lets calculate A*x for some x.
    //
    alglib::real_1d_array x = "[1,-1]";
    alglib::real_1d_array y = "[]";
    alglib::sparsemv(s, x, y);
    printf("%s\n", y.tostring(2).c_str()); // EXPECTED: [1.000,-5.000]
    return 0;
}
