Thursday, July 28, 2016

cake thief (knapsack problem)

Cake has weight and value. Given different types of cakes with infinite number of each type, and a capacity for duffel bag, get the max value a thief can steal.

ex:
cakes = [(7, 160), (3, 90), (2, 15)]
capacity = 20

returns (555, [(3, 90), (3, 90), (3, 90), (3, 90), (3, 90), (3, 90), (2, 15)])

There could be a cake with 0, +ve weight or value, ex: (0, 0), (1, 0), (0, 1).
cake:
    weight //0+
    value  //0+

max(cakes, capacity):
    for cake in cakes:
        if cake.value > 0 && cake.weight == 0:
            return int.max, yield-infinite(cake)
    maxvalue = {value = 0}
    maxcakes = new
    max(cakes, capacity, maxvalue, maxcakes, 
        bag: {weight = 0, value = 0, cakes = new})
    return maxvalue.value, maxcakes

max(cakes, capacity, maxvalue, maxcakes, bag):
    if bag.weight > capacity:
        return
    if bag.value > maxvalue.value:
        maxvalue.value = bag.value
        maxcakes.clear()
        maxcakes.add(cake for cake in bag.cakes)
    for cake in cakes:
        if cake.value == 0:
            continue
        bag.weight += cake.weight
        bag.value += cake.value
        bag.cakes.add(cake)
        max(cakes, capacity, maxvalue, maxcakes, bag)
        bag.weight -= cake.weight
        bag.value -= cake.value
        bag.cakes.removelast()

yield-infinite(cake):
    while true:
        yield cake
[Hat tip to IC]

No comments:

Post a Comment