Skip to content

Instantly share code, notes, and snippets.

@shonenada
Last active August 29, 2015 14:03
Show Gist options
  • Save shonenada/1e54fd9f97c82c3433c4 to your computer and use it in GitHub Desktop.
Save shonenada/1e54fd9f97c82c3433c4 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char string[1024];
} String;
typedef struct {
int size;
String dict[1024];
} CharDict;
void print_dict(CharDict* dict) {
int i;
for(i=0; i<dict->size; ++i) {
printf("%d %s\n", i, dict->dict[i].string);
}
}
void add_element(CharDict* dict, String* string) {
memcpy(dict->dict[dict->size].string, string, sizeof(String));
dict->size += 1;
}
void clean_dict(CharDict* dict) {
dict->size = 1;
dict->dict[0].string[0] = '\0';
}
int is_in_dict(CharDict* dict, char* string) {
int i;
for(i=0; i<dict->size; ++i) {
if (strcmp(dict->dict[i].string, string) == 0) {
return 1;
}
}
return 0;
}
void init_dict(CharDict* dict, String* string) {
int i;
char chr[2];
i = 0;
while((chr[0] = string->string[i]) != '\0') {
i++;
chr[1] = '\0';
if (!is_in_dict(dict, chr)) {
String string;
strcpy(string.string, &chr);
string.string[1] = '\0';
add_element(dict, &string);
}
}
}
int index_of(CharDict* dict, String* string) {
int i;
for(i=0; i<dict->size; ++i) {
if (strcmp(dict->dict[i].string, string->string) == 0) {
return i;
}
}
return -1;
}
void add_char_to_str(char* string, char chr) {
int size = strlen(string);
string[size] = chr;
string[size + 1] = '\0';
}
char* encode(CharDict* dict, String* string) {
clean_dict(dict);
init_dict(dict, string);
int i, idx;
char chr;
char output[1024] = "";
char prefix[1024] = "";
char temp[1024] = "";
i = 0;
while((chr = string->string[i]) != '\0') {
i += 1;
strcpy(temp, prefix);
add_char_to_str(temp, chr);
if (is_in_dict(dict, temp)) {
add_char_to_str(prefix, chr);
} else {
idx = index_of(dict, prefix);
if (idx == -1) {
printf("Error\n");
exit(EXIT_FAILURE);
}
add_char_to_str(output, (idx + 48));
add_char_to_str(prefix, chr);
add_element(dict, prefix);
prefix[0] = chr;
prefix[1] = '\0';
}
}
return output;
}
int main(int argc, char* argv[]) {
CharDict cdict;
printf("%s\n", encode(&cdict, argv[1]));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment