Run-length encoding/C: Difference between revisions

Content added Content deleted
m (→‎Unbuffered - Generative: minor reformat of code and comment)
mNo edit summary
Line 14: Line 14:
#include <string.h>
#include <string.h>


char *input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
const char *input = "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWWW";
char *output = "12W1B12W3B24W1B14W";
const char *output = "12W1B12W3B24W1B14W";


typedef void (*YIELDCHAR)(); /* yields via yield_init */
typedef void (*YIELDCHAR)(); /* yields via yield_init */
Line 45: Line 45:
#define YIELDS(type) BOOL (*yield)(type) = yield_init
#define YIELDS(type) BOOL (*yield)(type) = yield_init


ITERATOR gen_char_seq (char *s){
ITERATOR gen_char_seq (const char *s){
YIELDS(char);
YIELDS(char);
fflush(stdout);
fflush(stdout);
Line 79: Line 79:
}
}


char *zero2nine = "0123456789";
const char *zero2nine = "0123456789";


ITERATOR gen_decode (GENCHAR gen_char){
ITERATOR gen_decode (GENCHAR gen_char){
Line 94: Line 94:
}
}


main(){
int main(){
/* iterate through input string */
/* iterate through input string */
printf("Encode input: ");
printf("Encode input: ");
Line 108: Line 108:
OD;
OD;
printf("\n");
printf("\n");
return 0;
}</lang>
}</lang>
Output:
Output:
Line 185: Line 186:
}</lang>
}</lang>


In the following codes, encoding and decoding are implementend as "filters" which compress/decompress standard input to standard output writing ASCII strings; they will work as long as the input has no ASCII digits in it, and the compressed/original ratio of a "single group" will be less than or equal to 1 as long as the ASCII decimal representation's length of the repeat counter will be shorter than the length of the "group". It should be so except in the case the group is a single isolated character, e.g. B gives 1B (one byte against two compressed bytes)
In the following codes, encoding and decoding are implemented as "filters" which compress/decompress standard input to standard output writing ASCII strings; they will work as long as the input has no ASCII digits in it, and the compressed/original ratio of a "single group" will be less than or equal to 1 as long as the ASCII decimal representation's length of the repeat counter will be shorter than the length of the "group". It should be so except in the case the group is a single isolated character, e.g. B gives 1B (one byte against two compressed bytes)


'''Encoding filter'''
'''Encoding filter'''
Line 205: Line 206:
}
}
printf("%d%c", i, cp);
printf("%d%c", i, cp);
return 0;
}</lang>
}</lang>


Line 218: Line 220:
for(j=0; j < i; j++) printf("%c", c);
for(j=0; j < i; j++) printf("%c", c);
}
}
return 0;
}</lang>
}</lang>