Benjamin Hughes
Benjamin Hughes

Reputation: 73

How to add constraints to Linear Programming of the Knapsack Problem in R?

I was working through the code found at: https://sites.math.washington.edu/~conroy/2015/m381-aut2015/Rexamples/knapsack.r

I was wondering if anyone knows how to add a conditional constraint that only allows for a certain number of items in the knapsack. How would I modify the code to still optimize the value of the knapsack but only take a certain number of items?

# import the lpsolve library
library(lpSolve)

# objective function
knapsack.obj <- c(500,300,100,210,360,180,220,140,90)

#constraints
knapsack.con <- matrix(c(30,35,10,15,35,22,29,18,11),nrow=1,byrow=TRUE)
knapsack.dir <- c("<=")
knapsack.rhs <- c(100)

#solve
# Note when we call the lp function, we set all.bin=TRUE to indicate that all variables are 0 or 1
# If we just wanted to specify integer values generally, we would set all.int=TRUE
# The default for both of these options if FALSE
knapsackSolution <- lp("max",knapsack.obj,knapsack.con,knapsack.dir,knapsack.rhs,all.bin=TRUE) 
print("Solution is:")
print(knapsackSolution$solution)
print("Objective function value at solution is:")
print(knapsackSolution$objval)

Upvotes: 1

Views: 626

Answers (1)

chinsoon12
chinsoon12

Reputation: 25225

You can add it to the constraints as follows:

numItems <- 5
knapsack.con <- matrix(c(30,35,10,15,35,22,29,18,11, rep(1, length(knapsack.obj))), nrow=2, byrow=TRUE)
knapsack.dir <- c("<=", "==")
knapsack.rhs <- c(100, numItems)

Upvotes: 3

Related Questions