A Package to solve knapsack problem using 3 different approaches.
The knapsack is a discrete optimization problem where we have a sack that can filled with a limited weight w by adding number of items i = 1, ..., n, with a weight wi and a value vi to get the maximum value. This problem is NP-hard, meaning that it is ”at least as hard as the hardest problem in NP”
ref: (via)
devtools::load_all() library("knapsackProblems") set.seed(345) n <- 3000 knapsack_objects <- data.frame( w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000) ) head(knapsack_objects)
brute_force_knapsack(knapsack_objects[1:8,], w = 3500)
brute_force_knapsack(x = knapsack_objects[1:12,], w = 2000)
set.seed(42) n <- 16 knapsack_objects <- data.frame( w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000)) system.time(result1 <- brute_force_knapsack(x = knapsack_objects[1:12,], w = 2000))
dynamic_program(knapsack_objects[1:8,], w = 3500)
dynamic_program(x = knapsack_objects[1:12,], w = 2000)
set.seed(42) n <- 500 knapsack_objects <- data.frame( w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000)) system.time(result2<- dynamic_program(x = knapsack_objects[1:12,], w = 2000))
greedy_knapsack(knapsack_objects[1:800,], w = 3500)
greedy_knapsack(x = knapsack_objects[1:12,], w = 2000)
set.seed(42) n <- 1000000 knapsack_objects <- data.frame( w=sample(1:4000, size = n, replace = TRUE), v=runif(n = n, 0, 10000)) system.time(result3 <- greedy_knapsack(x = knapsack_objects[1:12,], w = 2000))
Paralellism is implemented in Brute Force algorithm to optimize performance of program. Usage of paralellism will be achieved by setting paralell parameter to TRUE in brute fore function.
Used for finding out the execution time of a function
library(microbenchmark) microbenchmark( "brute_force_knapsack"= result1, #n= 16 "dynamic_program" = result2, #n= 500 "greedy_knapsack" = result3 ,#n = 1000000 times = 1, unit = "us" )
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.