Skip to content

Instantly share code, notes, and snippets.

@abstractOwl
Created May 13, 2014 21:48
Show Gist options
  • Save abstractOwl/75175c81afad63428b98 to your computer and use it in GitHub Desktop.
Save abstractOwl/75175c81afad63428b98 to your computer and use it in GitHub Desktop.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct token_t
{
char token;
int count;
}
char *mk_string(token_t token)
{
int len = (int) floor(log10(token.count)) + 3;
char *new_s = malloc(sizeof(char) * len);
sprintf(new_s, "%c%d", token.token, token.count);
return new_s;
}
char *compress(char *s)
{
token_t tokens[strlen(s)];
int i, len;
int pos = 0; // Position in new_s
int count = 0;
int prev = -1; // Remember previous character
for (i = 0, len = strlen(s) + 1; i < len; i++) {
if (s[i] == prev) {
count++;
} else if (prev != -1) {
// Write char + count to file, exclude initial case
tokens[pos].token = prev;
tokens[pos].count = count;
pos++;
// Start seq for this char
prev = s[i];
count = 1;
}
}
// Max size is 2 * strlen(s) + 1 (for \0)
char *new_s = malloc(sizeof(char) * strlen(s) * 2 + 1);
for (int i = 0, len = strlen(s) + 1; i < len; i++) {
char *tmp_s = mk_string(tokens[i]);
strcat(new_s, tmp_s);
free(tmp_s);
}
if (strlen(new_s) > strlen(s)) {
free(new_s);
return s;
} else {
return new_s;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment