# Compressing a 2D array

Joey Ngo Source

I would like to compress a 2d array from the following input

``````Enter the array size (rowSize, colSize):
4 4
Enter the matrix (4x4):
1 1 1 0
0 0 1 1
1 1 1 1
0 0 0 0
``````

to this, where the number of 1's and 0's are specified.

``````compress2D():
1 3 0 1
0 2 1 2
1 4
0 4
``````

the following is my code

``````void compress2D(int data[SIZE][SIZE], int rowSize, int colSize)
{
int i , j , counter = 0, tempInt = data[0][0];
for (i = 0 ; i < rowSize ; i++)
{
for (j = 0 ; j < colSize ; j++ )
{
if (data[i][j] == tempInt)
counter++ ;
else
{
printf("%d %d " , tempInt,counter);
tempInt = data[i][j];
counter = 1;

}
}
if(counter!=0)
printf("%d %d",tempInt, counter);
counter = 0 ;
printf("\n");
}
}
``````

however this is my output

``````compress2D():
1 3 0 1
0 2 1 2
1 4
1 0 0 4
``````

all inputs will be binary

any help would be greatly appreciated!

c

answered 8 months ago Stephen Docy #1

As mentioned in the comments, you need to reset `tempInt` each time you start a new row

``````void compress2D(int data[SIZE][SIZE], int rowSize, int colSize)
{
int i, j, counter = 0, tempInt = data[0][0];
for (i = 0; i < rowSize; i++)
{
tempInt = data[i][0];                        // <--------

for (j = 0; j < colSize; j++)
{
if (data[i][j] == tempInt)
counter++;
else
{
printf("%d %d ", tempInt, counter);
tempInt = data[i][j];
counter = 1;

}
}
if (counter != 0)
printf("%d %d", tempInt, counter);
counter = 0;
printf("\n");
}
}
``````

answered 8 months ago cse #2

You can use following code. See it working here:

``````void compress2D(int data[SIZE][SIZE], int rowSize, int colSize)
{
int i , j , counter, tempInt;
for (i = 0 ; i < rowSize ; i++)
{
tempInt = data[i][0];
counter = 1;

for (j = 1 ; j < colSize ; j++ )
{
if (data[i][j] == tempInt)
counter++ ;
else
{
printf("%d %d " , tempInt,counter);
tempInt = data[i][j];
counter = 1;
}
}
if(counter)
printf("%d %d",tempInt, counter);
printf("\n");
}
}
``````

Note: Updated after last comment of OP(`0 1 1 2 0 1` , there are some cases where the output will be longer than the input itself).