Advertisement
cd62131

Run Length Encoding

May 5th, 2019
762
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.54 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. static int str_in(char *p, int size) {
  4.   if (!fgets(p, size, stdin)) {
  5.     return 0;
  6.   }
  7.   int len = 0;
  8.   for (; *p; ++p, ++len) {
  9.     if (*p == '\n') {
  10.       *p = '\0';
  11.       break;
  12.     }
  13.     if (*p < ' ' || ('0' <= *p && *p <= '9') || '~' < *p) {
  14.       return 0;
  15.     }
  16.   }
  17.   return len;
  18. }
  19. static void compress_sub(char **to, char prev, int *len, int c) {
  20.   if (2 < c) {
  21.     **to = '0' + c;
  22.     ++*to;
  23.     ++*len;
  24.   } else {
  25.     for (--c; c; --c, **to = prev, ++*to, ++*len) {
  26.       ;
  27.     }
  28.   }
  29. }
  30. static int compress(char *from, char *to) {
  31.   char prev = *to++ = *from++;
  32.   int len = 1, c = 1;
  33.   for (; *from; ++from) {
  34.     if (prev == *from && c < 9) {
  35.       ++c;
  36.       continue;
  37.     }
  38.     compress_sub(&to, prev, &len, c);
  39.     prev = *to++ = *from;
  40.     ++len;
  41.     c = 1;
  42.   }
  43.   compress_sub(&to, prev, &len, c);
  44.   *to = '\0';
  45.   return len;
  46. }
  47. static void decompress(char *from, char *to) {
  48.   char prev = *to++ = *from++;
  49.   int len = 1;
  50.   for (; *from; ++from) {
  51.     if (*from < '0' || '9' < *from) {
  52.       prev = *to++ = *from;
  53.       ++len;
  54.       continue;
  55.     }
  56.     for (int c = *from - '0' - 1; c; --c, *to++ = prev, ++len) {
  57.       ;
  58.     }
  59.   }
  60.   *to = '\0';
  61.   // return len;
  62. }
  63. int main(void) {
  64. #define N 16
  65.   char src[N], dest[N], cmp[N];
  66.   if (!str_in(src, N)) {
  67.     return 1;
  68.   }
  69. #undef N
  70.   printf("|%s| --> ", src);
  71.   compress(src, dest);
  72.   printf("|%s| --> ", dest);
  73.   decompress(dest, cmp);
  74.   printf("|%s| ", cmp);
  75.   printf("%d\n", strcmp(src, cmp));
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement