Cod sursa(job #1342490)

Utilizator bogdanstefanBogdan Stefan bogdanstefan Data 14 februarie 2015 02:13:12
Problema Convertor Scor 100
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.58 kb
#include <stdio.h>
#include <string.h>

#define MAX_LINE_SIZE 1024
#define MAX_KEY_SIZE 200000

// check if a string contains a number
int hasAlphanumerical(const char *s) {
  while (*s != '\0') {
    if (isalnum(*s))
      return 1;
    s++;
  }
  return 0;
}

// corrects the string
char* adjust(char *s) {
	while(!isdigit(*s) && *s != '"')
	    s++;
	    
	// if it is a string, only keep what's between the quotes
	if(*s == '"') {
	    s++;
    	char *last;
  		last = s + strlen(s) - 1;
  		while(last > s && *last != '"')
  			last--;
		*last = 0;
		return s;
	}
	
	// if it is a number, only preserve digits
	else {
		char *number = calloc(2*strlen(s), 1);
		strcpy(number, "");
		int count = 0;
		while(*s != 0) {
			if(isdigit(*s)) {
				number[count++] = *s;
				number[count] == '\0';
			}
			s++;
		}
	return number;
	}
return s;
}

int main() {
    // input/output
    freopen("convertor.in", "r", stdin);
    freopen("convertor.out", "w", stdout);

    char *keys[MAX_KEY_SIZE], *values[MAX_KEY_SIZE], buffer[MAX_LINE_SIZE], *token;
    int index = 1, keysLength = 0, valuesLength = 0, keysReady = 0;
    keys[0] = strdup("");

    // read line by line
    while (fgets (buffer, sizeof(buffer), stdin)) {
        // tokenize each line
        token = strtok(buffer, ",[{}]:");
        while(token) {
            // ignore residual tokens
            if(hasAlphanumerical(token)) {
				token = adjust(token);
                // odd indexes contain keys
                if(!keysReady && index % 2) {
                    if(strcmp(keys[0], token) == 0) {
                        keysLength = index / 2;
                        // if all the keys were read, stop reading them
                        keysReady = 1;
                    }
                    else {
                        keys[index / 2] =  strdup(token);
                        keysLength++;
                    }
                }
                // even indexes contain values
                else if(!(index % 2)) {
                    values[index / 2 - 1] = strdup(token);
                    valuesLength++;
                }
                index++;
            }
            token = strtok(NULL, ",[{}]:");
        }
    }

    // print keys
    for(index = 0; index < keysLength; index++)
        printf("%s,", keys[index]);
    printf("\n");

    //print values
    for(index = 0; index < valuesLength; index++) {
        printf("%s,", values[index]);
        if(index % keysLength == keysLength - 1)
            printf("\n");
    }
    return 0;
}