knitr::opts_chunk$set( collapse = TRUE, comment = "#>" )
devtools::install_github("stasinak/Adv_R6")
The only solution that is guaranteed to give a correct answer in all situations for the knapsack problem is using brute-force search, i.e. going through all possible alternatives and return the maximum value found. This approach is of complexity O(2n) since all possible combinations 2n needs to be evaluated.
library(AdvR6) AdvR6::brute_force_knapsack(x = knapsack_objects[1:8,], W = 3500) AdvR6::brute_force_knapsack(x = knapsack_objects[1:12,], W = 3500)
system.time(AdvR6::brute_force_knapsack(x = knapsack_objects[1:16,], W = 3500))
This algorithm can solve the knapsack problem exact by iterating over all possible values of w.
AdvR6::dynamic_knapsack(x = knapsack_objects[1:8,], W = 3500) AdvR6::dynamic_knapsack(x = knapsack_objects[1:12,], W = 3500)
system.time(AdvR6::dynamic_knapsack(x = knapsack_objects[1:500,], W = 3500))
This algorithm will not give an exact result (but it can be shown that it will return at least 50% of the true maximum value), but it will reduce the computational complexity considerably (actually to O(n log n) due to the sorting part of the algorithm).
AdvR6::greedy_knapsack(x = knapsack_objects[1:800,], W = 3500) AdvR6::greedy_knapsack(x = knapsack_objects[1:1200,], W = 2000)
system.time(AdvR6::greedy_knapsack(x = knapsack_objects[1:1000000,], W = 2000))
In this algorithm we realized if we use while loops instead of for loops we can gain speed because creating list or vector in for loop takes time. For optimizing our algorithm, we eliminate the elements which its weight is greater than the knapsack size, as a result we can gain some performance in our loops. We also create a parallelized version of this algorithm which divides the problem into iterations and we distributed these iterations to cores.
In this algorithm we gain speed because we vectorize the problem instead of putting and checing the same values until the end of row one by one.
This algorithm stops when it find the correct solution. Despite the fact that this algorithm is the fastest one we gained speed(again) because we sort the elements by heuristic instead of getting the max heuristic value in every iteration.
First Algorithm
ANALYSIS FOR FIRST
Optimized Algorithm
ANALYSIS FOR FIRST
First Algorithm
ANALYSIS FOR FIRST
Optimized Algorithm
ANALYSIS FOR FIRST
First Algorithm
ANALYSIS FOR FIRST
Optimized Algorithm
ANALYSIS FOR FIRST
AdvR6::brute_force_knapsack(x = knapsack_objects[1:8,], W = 3500)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.