Last active
June 20, 2018 14:44
-
-
Save zhiyb/000d8de80b040c88b59cf01d317ac640 to your computer and use it in GitHub Desktop.
An inefficient compression algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdint.h> | |
int main(int argc, char *argv[]) | |
{ | |
if (argc != 3) | |
return 1; | |
int seq_size = atoi(argv[1]); | |
int repeat = atoi(argv[2]); | |
uint8_t seq[seq_size]; | |
int c, i = 0; | |
uint16_t w = 0; | |
while ((c = getchar()) >= 0) { | |
int idx = i % seq_size; | |
int rep = i / seq_size; | |
i++; | |
if (rep != repeat) { | |
// Not yet repeated | |
putchar(c); | |
// Reset if mismatched | |
if (rep && c != seq[idx]) | |
i -= seq_size * rep; | |
seq[idx] = c; | |
} else if (c != seq[idx] || w == (uint16_t)-1) { | |
// Sequence mismatched or counter about to overflow | |
seq[idx] = c; | |
// Write counter and sequence then reset | |
fwrite(&w, sizeof(w), 1, stdout); | |
fwrite(seq, 1, idx + 1, stdout); | |
i -= seq_size * repeat; | |
w = 0; | |
} else if (!(i % seq_size)) { | |
// Sequence matched | |
i -= seq_size; | |
w++; | |
} | |
} | |
// End-of-file | |
int idx = i % seq_size; | |
int rep = i / seq_size; | |
if (rep == repeat) { | |
// Sequence repeated, write counter and remaining data | |
fwrite(&w, sizeof(w), 1, stdout); | |
fwrite(seq, 1, idx, stdout); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great~