Bg601
Bg601

Reputation: 49

Reconstructing an array in c

Given a sparse vector (more 0s than other elements), make a function to split the vector up into two vectors (one containing the elements, and the other containing the position of the elements. Make another function to reconstruct the source vector from the position and value arrays (including the 0s in the original source).

So this doesn't reconstruct it properly - and I don't understand why. I tested the arrays val and pos in the main function, but they don't have the right numbers in them.

Here's what I have so far:

for the efficient representation (splitting the source vector into two parts):

void efficient( const int source[], int val[], int pos[], int size)
{
int j = 0;

for (j = 0; j < size; j++)
{
    if (source[j] != 0)
    {
            val[j] = source[j]; 
            pos[j] = j;
    }
}
}

for the reconstruct function (m is size of source vector being reconstructed, n is size of position and value vectors):

void reconstruct( int source[], int m, const int val[], const int pos[], int n) {

int i = 0;
int j = 0;
int k = 0;

for (i = 0; i < m; i++)
    source[i] = 0; // sets all elements in source array equal to 0


for (j = 0; j < n; j++){
    source[pos[j]] = val[j];
    }


for (k = 0; k < m; k++)
    printf("%d ", source[k]);

}

and here's my main test function:

int main()
{
int i;
int size;
const int source[] = {0,0,23,0,-7,0,0,48};
int val[3] ;
int pos [3] ;

efficient(source,val,pos,8); // calls function efficient

reconstruct(source, 8, val, pos, 3); // calls function reconstruct with parameters source, source size = 8, value array, position array and size of value and position array
}

So this doesn't reconstruct it properly - and I don't understand why. I tested the arrays val and pos in the main function, but they don't have the right numbers in them.

Upvotes: 0

Views: 504

Answers (1)

David Schwartz
David Schwartz

Reputation: 182827

void efficient( const int source[], int val[], int pos[], int size)
{
    int j = 0;

    for (j = 0; j < size; j++)
    {
        if (source[j] != 0)
        {
                val[j] = source[j];  <-- HERE
                pos[j] = j;
        }
    }
}

You don't mean val[j]. You need a separate variable to count the number of entries in val and pos. Perhaps:

void efficient( const int source[], int val[], int pos[], int size)
{
    int j, p;

    for (j = 0, p = 0; j < size; j++)
    {
        if (source[j] != 0)
        {
                val[p] = source[j];
                pos[p] = j;
                ++p;
        }
    }
}

Upvotes: 2

Related Questions