Java Crate Packer

This was another quickly put together Reddit Challenge solution, so it's a very straight forward application. I make the assumption that every small crate you stick in the large crate has the same dimension, and this was just so I could crank out the solution sooner. There's nothing stopping me or you from using a for loop, asking how many small crates share the same dimensions, giving the dimensions, and storing all of those values in a data structure. You would need to be careful, but it's certainly doable, and really not that much more difficult than what I did.

The first step is typical, and just setting myself up for success. One thing you may notice is that I defined all of the variables I used on the same line. It's a trick you can use in languages such as Java or C++ when the data type will be the same across various variables to save space. I probably could have broken it up into two lines just for readability sake, but either way it works just fine.

variable initialization for all the crate dimensions

The next step is to just capture the input from the user. This part could have been in a while loop, asking for different dimensions of boxes to fit into the large box. Part of the problem if you get crazy though is that it can become a much more difficult problem quickly. It could even be turned into an optimization problem where you want to get as many small boxes into the large box as possible. Again, doable but not that easy. It would take a bit more time than I spent on all this code to figure all that out.

capture the dimensions from the user

The final part is just figuring out the math. This really could have easily been its own function. However, the problem was fairly simple and there was just not a whole lot of work to be done. Even here I'm just multiplying and dividing items. If I made more free time I would refactor this into a few different functions, but at the end of the day it was meant to be a quick solution anyway.

perform the math and figure out how many small crates fit in the large crate

All-in-all, another very straightforward and simple application. I did update some of the code prior to writing this article, but left the comments alone. As a result, you will notice some discrepancies between what they say and what is going on. That is not intentional by any means. Since this was written in Java you can find the code on Github here, or see the video below for a demonstration of the code working.