Search code examples
optimizationdata-structures

Variation of Bin Packing Problem with Constraints


Problem Definition
You have N items to be placed in M bins. Each item n has weight Ni and each bin 'm' has capacity of Mi items and Mj weight.

Solve with First Fit.

Data Input Types:

N<itemID, weight> = [(1, 10), (2, 12), (3, 6), (4, 15), (5, 2), (6, 10), (7, 15)]
M<binID, maxItems, maxWeight> = [('a', 2, 39), ('b', 4, 10), ('c', 5, 5), ('d', 4, 20)]

Although Python or C code is more preferable, you can answer with psuedo-code

Thank you


Solution

  • items = [(1, 10), (2, 12), (3, 6), (4, 15), (5, 2), (6, 10), (7, 15)]
    bins = [('a', 2, 39), ('b', 4, 10), ('c', 5, 5), ('d', 4, 20)]
    
    bin_capacities = {bin_id: {'maxItems': max_items, 'maxWeight': max_weight, 'currentItems': 0, 'currentWeight': 0} for bin_id, max_items, max_weight in bins}
    assignments = {bin_id: [] for bin_id, _, _ in bins}
    
    def first_fit(items, bin_capacities, assignments):
        for item_id, item_weight in items:
            placed = False
            for bin_id, capacity in bin_capacities.items():
                if capacity['currentItems'] < capacity['maxItems'] and capacity['currentWeight'] + item_weight <= capacity['maxWeight']:
                    assignments[bin_id].append((item_id, item_weight))
                    capacity['currentItems'] += 1
                    capacity['currentWeight'] += item_weight
                    placed = True
                    break
            if not placed:
                print(f"Item {item_id} with weight {item_weight} could not be placed in any bin.")
        return assignments
    
    assignments = first_fit(items, bin_capacities, assignments)
    
    for bin_id, items in assignments.items():
        print(f"Bin {bin_id} contains items: {[i[0] for i in items]} \t {sum([i[1] for i in items])}")
    

    Output:

    Item 6 with weight 10 could not be placed in any bin.
    Item 7 with weight 15 could not be placed in any bin.
    Bin a contains items: [1, 2]     22
    Bin b contains items: [3, 5]     8
    Bin c contains items: []         0
    Bin d contains items: [4]        15