Skip to content

Instantly share code, notes, and snippets.

@rsampaio
Created December 23, 2010 05:30
Show Gist options
  • Save rsampaio/752607 to your computer and use it in GitHub Desktop.
Save rsampaio/752607 to your computer and use it in GitHub Desktop.
facebook puzzle - fun with dynamic memory and bigraphs
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/errno.h>
#define MAX_LINE 1024
typedef struct group {
char name[MAX_LINE];
struct group **votes;
int side;
} group_t;
group_t * group_find(group_t **group, char *name, int group_size)
{
int i;
for(i=0; i<group_size; i++) {
if ((strncmp(group[i]->name, name, strlen(group[i]->name))) == 0)
return group[i];
}
return NULL;
}
void group_print(group_t **group, int group_size)
{
int i, zero = 0, one = 0;
for(i=0; i<group_size; i++) {
if (strlen(group[i]->name) > 0 && group[i]->side == 0)
zero++;
else
one++;
}
printf("%d %d\n", zero, one);
}
int main(int argc, char **argv)
{
FILE *fd;
int j = 0, i = 0, line_c = 0, group_size = 0, group_c = 0, group_last = 0;
char **lines = NULL, buf[MAX_LINE];
char *name = NULL, *n_votes = NULL;
group_t **group = NULL, *cur = NULL, *new = NULL;
fd = fopen(argv[1], "r");
lines = (char **) malloc(sizeof(char*));
while ((fgets(buf, MAX_LINE, fd)) != NULL) {
*(lines + line_c) = (char*) malloc(strlen(buf) * sizeof(char));
memcpy(*(lines + line_c), buf, strlen(buf) - 1);
line_c++;
}
group_size = atoi(lines[0]);
group = (group_t **) malloc(group_size * sizeof(group_t*));
group_c = 0;
for (i=1; i<line_c; i++) {
name = strtok(lines[i], " ");
n_votes = strtok(NULL, " ");
if (n_votes != NULL && atoi(n_votes) > 0) {
cur = group_find(group, name, group_c);
if (cur == NULL) {
group[group_c] = (group_t *) malloc(sizeof(group_t));
memcpy(group[group_c]->name, name, sizeof(name));
group_last = group_c;
cur = group_find(group, name, ++group_c);
}
cur->votes = (group_t **) malloc(atoi(n_votes) * sizeof(group_t));
for (j=0; j<atoi(n_votes); j++) {
new = group_find(group, lines[i+j+1], group_c);
if (new == NULL) {
group[group_c] = (group_t *) malloc(sizeof(group_t));
memcpy(group[group_c]->name, lines[i+j+1], sizeof(lines[i+j+1]));
group[group_c]->side = cur->side == 0 ? 1 : 0;
cur->votes[j] = group_find(group, name, ++group_c);
new = cur->votes[j];
}
else {
group[group_last]->side = new->side == 0 ? 1 : 0;
}
}
i+=atoi(n_votes);
}
}
group_print(group, group_c);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment