Pages

Sunday, 29 October 2023

Chapter 27 // Exercise 12 - Principles & Practice Using C++

In this exercise I'm using Visual Studio 2022 and ISO C11 Standard.

Chapter 27 // Exercise 12

Implement a (C-Style string, int) lookup table with operations such as find(struct table*, const char*), insert(struct table*, const char*, int) and remove(struct table*, const char*). The representation of the table could be and array of a struct pair or pair of arrays (const char*[] and int*); you choose. Also choose return types for your functions. Document your design decisions.

I originally did a really simple hash function however ended up with collision in the table quickly. I did some searching around and came across the terms "linear probing" where we keep going through slots to find a new one, wrapping round to beginning if needed.

The implementation isn't perfect but it'll do. For my design decisions:

Representation: I chose an array of struct pairs because it keeps the key-value pairs together, which makes it more intuitive.

Return Types: For find(), I return the int value associated with the key. If the key isn't found, I' return a special value, like -1.
For insert(), I return 0 if the insertion was successful and -1 if not (for example, if the table is full).
For remove(), I return 0 if the key was successfully removed and -1 if the key was not found.

Handling Collisions: For simplicity, I handled simple collisions only. This means the table has a fixed size, and if it's full, you can't insert more items.

Capacity: The table has a fixed size, which for this example, is set to 100. it will wrap round to find free slots but after that it won't insert any more.

No comments:

Post a Comment