I have a two-dimensional integer array A(length m, width n) saved at an Address in MIPS. Out of this array, I would like to create another array B, which only contains the non-zero values from our array A. How would one go about implementing that from a pseudocode point of view?

My idea is to traverse through the array A row by row (with each row as a 1-Dimensional array). That means subdividing the Array A into n 1-Dimensional arrays and filtering out the non-zero elements with a for loop.

Does this approach sound credible?

1

There are 1 best solutions below

0
On

Two-dimensional arrays are really just one-dimensional arrays in memory, so if you are not concerned about looping through in a particular order, you can loop through the array in memory (m*n) to save some instructions. Otherwise you can traverse row-by-row as you have said.

The basic idea I would use is have the array B simulate pushing to a stack. This will leave some zeros at the end and you will have the size of the nonzero "stack". Each time you add an element to the array, you increase the "stack" size.

Psuedocode:

int b[m*n];

int b_size = 0;
for (int i=0; i<m*n; i++)
{
    if (a[i] != 0) 
    {
        b[b_size] = a[i];
        b_size++;
    }
}

Hopefully you can figure out how to translate this into MIPS from here.