2

I have a function compress2d() that takes as input a 2-dimensional array (10x10) of binary data, compresses each row of the array by replacing each run of 0s or 1s with a single 0 or 1 and the number of times it occurs, and prints on each line the result of compression. For example, the row with data 0011100011 may be compressed into 02130312.

eg:

input:

1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
1 1 1 1 1 0 0 0 0 0 
0 0 0 0 0 1 1 1 1 1 
1 1 1 1 1 0 0 0 0 0 
0 0 0 0 0 1 1 1 1 1 
1 1 1 1 1 0 0 0 0 0 
0 0 0 0 0 1 1 1 1 1 
1 1 1 1 1 0 0 0 0 0 
0 0 0 0 0 1 1 1 1 1 

Desired Output:

1 5 0 5  
0 5 1 5  
1 5 0 5  
0 5 1 5  
1 5 0 5  
0 5 1 5  
1 5 0 5  
0 5 1 5  
1 5 0 5  
0 5 1 5 

But i am getting:

1 5
1 4
1 4
1 4
.
.
.
.
1 4

Here is my code:

  void compress2D(int data[SIZE][SIZE])
  {

    int i,j=0, target, count=1, location=1;
    for (i = 0; i < SIZE; i++) {
        for (j = 0; j < SIZE; j++) {
            if (data[i][j] == data[i][j+1] && (j+1) < 10)
                count++;
            else {
                data[i][location] = count;
                data[i][location+1] = data[i][j+1];
                count = 1;
                location +=2;
            }
        }

        data[i][location] = '\0';
        location = 1;
        count = 0;
    }
    for (i = 0; i < SIZE;i++) {
        for (j = 0; data[i][j] != '\0'; j++) {
            printf("%d ", data[i][j]);
        }
        printf("\n");
    }
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
Denise
  • 139
  • 1
  • 2
  • 12
  • Try this: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ and https://stackoverflow.com/questions/2069367/how-to-debug-using-gdb – Yunnosch Oct 07 '17 at 06:24
  • How would you compress `1010101010`? By your logic, you would have actually expanded this to something like: `11011101110111011101` (<-the sequence may not be perfect but you get the idea) – babon Oct 07 '17 at 06:30
  • You're accessing outside the array when you use `data[i][j+1]` and `j == SIZE-1`. – Barmar Oct 07 '17 at 06:34

1 Answers1

0

'\0' is the same as 0. You never see the 0 values in your compressed array because the printing loop stops when data[i][j] == '\0', which is the same as data[i][j] == 0. You need to use a value that can't possibly exist in the compressed data to signal the end of a row. You could use SIZE+1, since the largest possible run is SIZE copies of the same value.

So change:

data[i][location] = '\0';

to:

data[i][location] = SIZE+1;

and change:

for (j = 0; data[i][j] != '\0'; j++)

to:

for (j = 0; data[i][j] != SIZE+1; j++)
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thank you so much for explaining it to me. Much clearer now. does it means that i have to declare variable num? @barmar – Denise Oct 07 '17 at 08:11
  • Sorry, meant `SIZE` (I must have been thinking of a different question) – Barmar Oct 07 '17 at 08:13