Skip to content

Instantly share code, notes, and snippets.

@zhiyb
Last active June 20, 2018 14:44
Show Gist options
  • Save zhiyb/000d8de80b040c88b59cf01d317ac640 to your computer and use it in GitHub Desktop.
Save zhiyb/000d8de80b040c88b59cf01d317ac640 to your computer and use it in GitHub Desktop.
An inefficient compression algorithm
#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;
}
@Ruilx
Copy link

Ruilx commented Jun 20, 2018

Great~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment