Continue working on Knapsack.

This commit is contained in:
Felix Martin 2019-12-09 16:34:53 -05:00
parent dc04e489fe
commit 4a7034225d
3 changed files with 31 additions and 28 deletions

1
.gitignore vendored
View File

@ -1,2 +1,3 @@
*.sublime-workspace
__pycache__
*.pyc

View File

@ -70,43 +70,48 @@ def solve_knapsack_depth_first_search(knapsack):
def get_max_value(from_index, capacity):
value = 0
items = knapsack.items
for i in range(from_index, num_items):
item = knapsack.items[i]
if item.weight <= capacity:
value += item.value
capacity -= item.weight
else:
value += int((item.weight / knapsack.capacity) * item.value) + 1
#value += int((item.weight / capacity) * item.value) + 1
return value
value += int((capacity / item.weight) * item.value)
break
return value
def search(index, capacity, value, path, result):
if capacity < 0:
return
if value > result["objective"]:
result["objective"] = value
result["path"] = path
result["path"] = list(path)
if capacity <= 0:
return
if index == num_items:
return
# print("--- search")
# print("Index: {} capacity: {}, value: {}".format(index, capacity, value))
# print("Path {}".format(path))
# Take current item.
max_value = get_max_value(index, capacity)
if value + max_value > result["objective"]:
item = knapsack.items[index]
new_index = index + 1
new_path = path + [1]
new_capacity = capacity - item.weight
new_value = value + item.value
search(new_index, new_capacity, new_value, new_path, result)
item = knapsack.items[index]
# print("max_value: {}".format(max_value))
max_value_not = get_max_value(index + 1, capacity)
# print("max_value_not: {}".format(max_value_not))
if item.weight <= capacity and value + max_value > result["objective"]:
path.append(1)
search(index + 1, capacity - item.weight,
value + item.value, path, result)
path.pop()
# Do not take current item.
new_index = index + 1
if value + get_max_value(new_index, capacity) > result["objective"]:
new_path = path + [0]
search(new_index, capacity, value, new_path, result)
if value + max_value_not > result["objective"]:
path.append(0)
search(index + 1, capacity, value, path, result)
path.pop()
def correct_path(path):
path = path + [0] * (num_items - len(path))

View File

@ -1,4 +1,4 @@
#!/usr/bin/python
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import knapsack
@ -7,12 +7,9 @@ import knapsack
def solve_it(input_data):
# Modify this code to run your optimization algorithm
k = knapsack.input_data_to_knapsack(input_data)
if len(k.items) <= 200:
r = knapsack.solve_knapsack_dynamic(k)
elif len(k.items) == 400:
r = knapsack.solve_knapsack_depth_first_search(k)
else:
r = knapsack.solve_knapsack_greedy(k)
r = knapsack.solve_knapsack_dynamic(k)
# r = knapsack.solve_knapsack_depth_first_search(k)
# r = knapsack.solve_knapsack_greedy(k)
return knapsack.result_to_output_data(r)