Inspired by a real-world problem of packing stacked chairs into a store room, the Chair Problem aims to figure out how to optimize a limited amount of space (the store room) for a given amount of rigid objects (the stacked chairs). The problem assumes that the room and chairs are square or rectangular in shape, the chairs do not sag to one side upon stacking (thus occupying more space) and there is no gap between each chair stack.
The problem lends itself quite naturally to the OOP model. Here, we try to model how the room and chairs interact with each other. The room is a space and the chairs occupy space. Thus, we can create a class called Space
that accepts the length and width for a Space
object. The chairs, on the other hand, consist of stacks that have several unique properties, including the total number of chairs, the number of chairs per stack and the number of stacks. We can extend the functionality of the Space
class and include these properties with a new class called Stack
. We also add a new method called setSpace()
to determine the available space based on the dimensions of the stack and the number of stacks that can fit into that space.
The problem was initially solved using C++. The C++ code was then rewritten into its equivalent Java and Python code for comparison. Unsurprisingly, the Java code was implemented with only slight changes from the original C++ code. However, the Python code needed more reworking due to the many differences in terms of syntax and Python's dynamic typing.
It is worth noting that Python does not have explicit private and protected variables (see access modifiers). Instead, these variables are denoted by convention with a double underscore (e.g. __foo
) for private variables and single underscore (e.g. _bar
) for protected variables. This is largely due to Python not having any actual data hiding and relying on the programmer to be responsible for not modifying any class variables by accident.
More stack objects can be added based on the Stack
class. Chairs are merely used as an example. Stacks of different objects (e.g. tables, books, pancakes(!), etc.) could interact with each other in the room, but that is a topic for another day.