Background:

  • So we are dealing with Xend API to calculate shipping.
  • Xend can process one waybill per customer per order.
  • A customer can have multiple different size and weight products in one order.
  • Xend API accepts only 1 Width, Height, Depth and Weight to generate a waybill.

Problem:

We can send Xend how much it would cost to ship each product then add the total together and show the customer on checkout, however Xend only accepts 1 Width, Height, Depth and Weight to generate the actual waybill. This means that what we tell the customer the shipping cost is before they checkout could be different shipping cost after we generate a waybill. Yes we care about accurately calculating the cost for shipping (but we are also considering adding a 1-2% padding in case)

Find:

Based on all the possible arrangements of N boxes find the most optimal W x H x D

Solution:

  • We spent about 3 hours drawing boxes on the whiteboard (bad idea)
  • We tried to use our best mathematicians (our best minored in math) (again bad idea)
  • We broke it down to sub problems and Computer Math and came up with something that could work.

Logic:

  1. Find total Volume (w*h*d)[+(w*h*d)..]
  2. Collect all possible width height and depth values, sort each from lowest to highest
  3. Find all possible sum permutations for width, then for height, then for width
    • Example: sum permutations for width ranges 1,2,3 would be 1, 2, 3, 4, 5, 6
    • We need this because in no way could the final value for width be 1.5 for example based on the example (3a.)
  4. Find all possible combinations of Width, Height and Depth based on the permutations calculated on (3.)
  5. Store all combinations where the total volume is equal or greater than the total Volume from (1.)
    • This is because it is not possible that the final volume could be less than the actual Volume (1.)
    • For Volumes greater than (1.) it means that's dead space.
  6. Sort all combinations from (5.) Ascending, the first result will be the most accurate Volume
  7. It is possible that the most accurate volume still could have different dimensions
    • Example: Volume 16 can be 2x2x4 or 4x4x1 or 2x1x8 or 16x1x1
    • Find the sum of W+H+D for each and the smallest sum would be the even more accurate dimensions.
    • Example: from (7a.) 2+2+4 = 8, 4+4+1 = 9, 2+1+8 = 11, 16+1+1 = 18 .... So our script would choose 2 x 2 x 4
X X