Cod sursa(job #1342317)

Utilizator bogdanstefanBogdan Stefan bogdanstefan Data 13 februarie 2015 20:33:10
Problema Convertor Scor 80
Compilator c Status done
Runda rosedu_cdl_2015 Marime 2.24 kb
#include <stdio.h>
#include <string.h>

#define MAX_LINE_SIZE 1024
#define MAX_KEY_SIZE 10000

// check if a string is whitespace only
int isWhitespace(char *s) {
  while (*s != '\0') {
    if (!isspace(*s))
      return 0;
    s++;
  }
  return 1;
}

// trim the spaces the string begins with
char* trimLeadingSpaces(char *s) {
	while (isspace(*s))
		 s++;
	return s;
}

void printKeys(char** keys, int keysLength) {
	int index;
	for(index = 0; index < keysLength; index++)
		printf("%s,", keys[index]);
		printf("\n");
}

void printValues(char** values, int valuesLength) {
	int index;
	for(index = 0; index < valuesLength; index++) {
        printf("%s,", values[index]);
	}
			printf("\n");
}

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 whitespace
			if(!isWhitespace(token)) {
				token = trimLeadingSpaces(token);
				// odd indexes contain keys
				
				if(keysReady && (strcmp(keys[0], token) == 0))
				    printf("\n");

				else if(!keysReady && index % 2) {
				 	if(strcmp(keys[0], token) == 0) {
				    	keysLength = index / 2;
				    	// if all the keys were read, stop reading them
				    	// and print keys + first set of values
						keysReady = 1;
						printKeys(keys, keysLength);
						printValues(values, valuesLength);
					}
					else {
						keys[index / 2] = strdup(token);
						keysLength++;
					}
				}

				// even indexes contain values
				else if(!(index % 2)) {
        			if(!keysReady) {
						values[index / 2 - 1] = strdup(token);
						valuesLength++;
					}
					// after keys are ready, print values on the go
					else
					    printf("%s,", token);
				}
		    	index++;
			}
			token = strtok(NULL, ",[{}]:\"");
		}
	}

	if(!keysReady) {
        printKeys(keys, keysLength);
		printValues(values, valuesLength);
	}
	
	//print values

	return 0;
}