Find the Best Size Container

Not everything in the real world appreciates the holy computer numbers. These are binary values that parallel the powers of 2: 1, 2, 4, 8, 16, 32, 64, and so on.

A common computer puzzle is how to allocate storage specific to those holy numbers, especially when the sizes of items that you’re working with don’t exactly line up to a specific holy computer number.

For example, suppose you have a string of 11 bytes. You might create a storage container 16 bytes wide to hold those bytes. You don’t have to do so, but when you built a 16-byte buffer, the processor can more effectively access the information.

Internally, the compiler prefers to align values at specific memory locations. If you use a debugger, you’ll see how variables sit at address offsets that end in 0, 4, 8, and C. This is why in my code I set buffer sizes to a holy number. It’s not a requirement, but the practice uses memory more efficiently.

To put it another way, suppose that you’re tasked with organizing a pile of 2-by-4s. Each board is a different length, but you must set them into containers that are exactly 16, 32, 48, and 64 inches tall. So you would take a 15-inch long board and put it into the 16-inch tall container. The 39-inch board would fit into the 48-inch cubby, and so on.

For this month’s Exercise, you start with an int array of values:

    int lengths[COUNT] = { 4, 28, 52, 16, 35 };

Your job is to process each of the COUNT (five) values to determine how they best-fit into a container that is a multiple of 16 units in size.

Obviously, I don’t want you to create a single 64-unit container and just stick everything into it. That’s not the solution. In fact, here’s the output from my solution:

Length of 4 fits into 16
Length of 28 fits into 32
Length of 52 fits into 64
Length of 16 fits into 16
Length of 35 fits into 48

Your solution must determine which multiple of 16 is closest to the value given and set a container size accordingly. Your code must also detect when a value is identical to a multiple of 16 and set the value to match.

Please try this Exercise on your own before you check out my solution.

Leave a Reply