Skip to content

Instantly share code, notes, and snippets.

@subhacom
Created September 13, 2018 19:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subhacom/4138eae91357f01af67c2e3dac7236ca to your computer and use it in GitHub Desktop.
Save subhacom/4138eae91357f01af67c2e3dac7236ca to your computer and use it in GitHub Desktop.
A small C program to compute Lempel-Ziv complexity of a string
/* lzcomplexity.c ---
* Author: Subhasis Ray
* Created: Thu Sep 13 11:54:21 2018 (-0400)
* Last-Updated: Thu Sep 13 14:01:18 2018 (-0400)
* By: Subhasis Ray
* Version: $Id$
/* This implements the algorithm described by Casper and Schu"ster, 1987, Physical Review A:
"Easily calculable measure for the complexity of spatiotemporal patterns". */
/* Code: */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int lzcomplexity(char *ss){
int ii = 0, kk = 1, el = 1, kmax = 1, cc = 1, nn;
nn = strlen(ss);
while (1){
if (ss[ii + kk - 1] == ss[el + kk - 1]){
kk++;
if ((el + kk) > nn){
++cc;
break;
}
} else {
if ( kk > kmax ){
kmax = kk;
}
++ii;
if (ii == el){
++cc;
el += kmax;
if ((el + 1) > nn){
break;
}
ii = 0;
kk = 1;
kmax = 1;
} else {
kk = 1;
}
}
}
return cc;
}
int test(){
char data[256] = "1001111011000010\0";
printf("lzc=%d\n", lzcomplexity(data));
return 0;
}
int main(int argc, char **argv){
FILE * input;
char * buffer;
int size;
int length;
if (argc < 2){
printf("Require an input file. Usage %s filename\n", argv[0]);
return -1;
}
input = fopen(argv[1], "rb");
fseek(input, 0L, SEEK_END);
size = ftell(input);
printf("File size: %d\n", size);
fclose(input);
input = fopen(argv[1], "r");
buffer = (char*) calloc(size+1, sizeof(char));
fgets(buffer, size, input);
fclose(input);
printf("Read %s\n", buffer);
length = strlen(buffer);
printf("Length of string including terminal new line: %d\n", length);
if (buffer[length - 1] == '\n'){
buffer[length - 1] = '\0';
length--;
}
printf("Length of string without terminal new line: %d\n", length);
printf("Lempel-Ziv complexity of this string of length %d is %d\n", length, lzcomplexity(buffer));
return 0;
}
/* lzcomplexity.c ends here */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment