#include #include #include #include #include "01_hashtable.c" house **process_next_house(house **hash_table, uint32_t *table_size, int32_t *x, int32_t *y, uint32_t *hcount) { //first check to see if we need to enlarge the hash table if (hash(*x, *y) > *table_size - 1) { *table_size = *table_size * 2; hash_table = ht_resize(hash_table, *table_size / 2, *table_size); } //process next house house *loc = ht_lookup(hash_table, *x, *y); if (loc == NULL) { (*hcount)++; ht_insert(hash_table, *x, *y, 1); } else { (loc->p)++; } return hash_table; } int main() { FILE *file = fopen("input", "r"); if (file == NULL) { perror("main: error opening file."); return 1; } uint32_t table_size = 25; house **hash_table = ht_init(table_size); /* Santa */ int32_t x_s = 0; int32_t y_s = 0; ht_insert(hash_table, x_s, y_s, 1); //initial house at (0, 0) uint32_t hcount = 1; /* Robo-Santa */ int32_t x_r = 0; int32_t y_r = 0; enum toggle { santa, robo_santa }; enum toggle turn = robo_santa; int32_t c; while ((c = fgetc(file)) != EOF) { turn = turn ^ robo_santa; //toggle turn switch(turn) { case santa: if (c == '^') { y_s++; hash_table = process_next_house(hash_table, &table_size, &x_s, &y_s, &hcount); } else if (c == 'v') { y_s--; hash_table = process_next_house(hash_table, &table_size, &x_s, &y_s, &hcount); } else if (c == '>') { x_s++; hash_table = process_next_house(hash_table, &table_size, &x_s, &y_s, &hcount); } else if (c == '<') { x_s--; hash_table = process_next_house(hash_table, &table_size, &x_s, &y_s, &hcount); } break; case robo_santa: if (c == '^') { y_r++; hash_table = process_next_house(hash_table, &table_size, &x_r, &y_r, &hcount); } else if (c == 'v') { y_r--; hash_table = process_next_house(hash_table, &table_size, &x_r, &y_r, &hcount); } else if (c == '>') { x_r++; hash_table = process_next_house(hash_table, &table_size, &x_r, &y_r, &hcount); } else if (c == '<') { x_r--; hash_table = process_next_house(hash_table, &table_size, &x_r, &y_r, &hcount); } break; default: perror("main: turn error."); return -1; } } if (ferror(file)) { perror("main: error reading from file."); return -1; } fclose(file); printf("unique houses: %u\n", hcount); for (uint32_t i = 0; i < table_size; i++) { free(hash_table[i]); } free(hash_table); return 0; }