/* * counters_intersect.c - test intersection of two counters * * CS50, Spring 2022 */ #include #include #include "libcs50/counters.h" #include "libcs50/memory.h" /******** local data types *******/ struct twocts { counters_t *result; counters_t *another; }; /******** local function prototypes *******/ void counters_intersect(counters_t* ct1, counters_t* ct2); void intersect_helper(void *arg, const int key, const int count); static inline int min(const int a, const int b) { return (a < b ? a : b); } /******** main *******/ int main() { // create two counters for demo counters_t *c1 = assertp(counters_new(), "counters_new() failed"); counters_t *c2 = assertp(counters_new(), "counters_new() failed"); // init counters 1 counters_set(c1, 3, 6); counters_set(c1, 4, 7); counters_set(c1, 5, 1); counters_set(c1, 7, 4); // init counters 2 counters_set(c2, 1, 3); counters_set(c2, 3, 2); counters_set(c2, 5, 4); counters_set(c2, 6, 6); counters_set(c2, 7, 3); // take the intersection, store the results in c1 counters_intersect(c1, c2); counters_print(c1, stdout); printf("\n"); // clean up counters_delete(c1); counters_delete(c2); return 0; } // TODO: fill in this function void counters_intersect(counters_t* ct1, counters_t* ct2) { assertp(ct1, "counters 1 invalid"); assertp(ct2, "counters 2 invalid"); struct twocts args = {ct1, ct2}; counters_iterate(ct1, &args, intersect_helper); } void intersect_helper(void *arg, const int key, const int count) { struct twocts *two = arg; counters_set(two->result, key, min(count, counters_get(two->another, key))); }