Jordan Iatro
Jordan Iatro

Reputation: 297

Compress char data

I have a 5 x 10 char matrix and I am suppose to compress it like a run length encoding.

    printf("Enter your data (5x10) of characters: \n");
    for (i = 0; i < SIZE1; i++)
    for (j = 0; j < SIZE2; j++)
        scanf("%c", &matrix2[i][j]);
    printf("\n");
    compress(matrix2);
    break;  

void compress(char data[SIZE1][SIZE2])
{
    int row, column, count=1;
    for (row = 0; row < SIZE1; row++)
    {
        for (column = 0; column < SIZE2; column++)
        {
            if (data[row][column] == data[row][column + 1])
            {
                count++;
            }
            else
            {
                printf("%c%d", data[row][column], count);
                count = 1;
            }
        }
    }
}

This is my code but I do not understand why my output will always have a 1 in front. Input:

aaabbbcccd
aabbccddee
aaaaaaaaaa
abcabcabca
aaabbbcccc

output:

a3b3c3d1
1a2b2c2d2e2
1a10
1a1b1c1a1b1c1a1b1c1a1
1a3b3

expected output:

a3b3c3d1
a2b2c2d2e2
a10
a1b1c1a1b1c1a1b1c1a1
a3b3c4

Upvotes: 1

Views: 258

Answers (3)

chux
chux

Reputation: 153488

Change the data entry. Have it deal with \n and error detection.

printf("Enter your data (%dx%d) of characters: \n", SIZE1, SIZE2);
for (i = 0; i < SIZE1; i++) {
  char buffer[(SIZE2 + 2)*2];  // Consider IO buffers 2x the needed size
  if (fgets(buffer, sizeof buffer, stdin) == NULL) 
    Handle_EndOfFileOrIOError();

  size_t len = strlen(buffer);
  if (len != SIZE2+1 || buffer[len-1] != '\n') 
    Handle_UnexpectDataLengthError(buffer, len);

  for (j = 0; j < SIZE2; j++) {
    matrix2[i][j] = buffer[j];
  }
  // or simply memcpy(matrix2[i], buffer, SIZE2);

printf("\n");
compress(matrix2);
break;  

Upvotes: 0

problemPotato
problemPotato

Reputation: 609

I believe the commenters are suggesting a change like so:

    printf("Enter your data (5x10) of characters: \n");
    for (i = 0; i < SIZE1; i++)
    for (j = 0; j < SIZE2; j++)
        scanf("%c", &matrix2[i][j]);
    printf("\n");
    compress(matrix2);
    break;  

void compress(char data[SIZE1][SIZE2])
{
    int row, column, count=1;
    for (row = 0; row < SIZE1; row++)
    {
        for (column = 0; column < SIZE2; column++)
        {
            if (data[row][column] == data[row][column + 1])
            {
                count++;
            }
            else
            {
                if (data[row][column] != '\n')
                {
                    printf("%c%d", data[row][column], count);
                    count = 1;
                }
            }
        }
    }
}

Upvotes: 0

Sebastian &#196;rleryd
Sebastian &#196;rleryd

Reputation: 1824

It is counting the newline character too.

Upvotes: 2

Related Questions