Search code examples
javaalgorithmbusiness-logic

Split shipping cost by weight across items in cart


I have two items in the cart item 1= $70 and item 2= $100 and i also have the total shipping i can charge, which is $15. While accepting this order Im trying to split the $15 shipping between item1 and item2 in a weighted manner based on the price. What is the best algorithm to split this and what is the logic/calculation look like ?

Any thoughts helpful, thanks !


Solution

  • I don't know Java, but since you included no Java code, I'll just give pseudocode to how to do this:

    a = 70 / (70 + 100)
    b = 100 / (70 + 100)
    

    This normalizes the two values, and then you can just multiply a and b with $15 to get the proper ratio. In this case, a is 0.41 and b is 0.59

    Then:

    ratio_item_a = 15 * a
    ratio_item_b = 15 * b
    

    ratio_item_a is 6.18 and ratio_item_b is 8.82