Founds

Alien Language

My solution for the "Alien Language" task of Google Code Jam 2009 qualification round (in C language):


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <regex.h>

main() {
  char str[4096];
  char *data, *p;
  regex_t reg;
  int L, D, N;
  size_t i, x;
  int rc, res;

  fgets(str, sizeof(str), stdin);
  sscanf(str, "%d %d %d", &L, &D, &N);

  data = (char*)malloc((L+1) * (D + 1));
  if (data == NULL) {
    fprintf(stderr, "Ops, no memory for %d bytes.\n", (L+1) * (D + 1));
    exit(1);
  }

  
  for (i = 0; i < D; i++) {
    fgets(str, sizeof(str), stdin);
    sscanf(str, "%s", data + i * (L + 1));
  }

  for (i = 0; i < N; i++) {
    fgets(str, sizeof(str), stdin);
    str[strlen(str) - 1] = '\0';
    for(p = strchr(str, '('); p != NULL; p = strchr(p, '(')) *p = '[';
    for(p = strchr(str, ')'); p != NULL; p = strchr(p, ')')) *p = ']';
    if (regcomp(&reg, str, REG_EXTENDED | REG_NOSUB) != 0) {
      fprintf(stderr, "Case #%d: Err. for: %s\n", (i+1), str);
      continue;
    }
    res = 0;
    for (x = 0; x < D; x++) {
      if ((rc = regexec(&reg, data + x * (L + 1), 0, NULL, 0)) == 0) res++;
    }
    printf("Case #%d: %d\n", i + 1, res);
    regfree(&reg);
  }
	

  regfree(&reg);
  free(data);
  return 0;
}