The website http://rosettacode.org/wiki/Knapsack_problem/Unbounded describes a fanciful trip by a traveler to Shangri La. Upon leaving, the traveler is allowed to take as much of three valuable items as they like, as long as they fit in a knapsack. A maximum of 25 weights can be taken, with a total volume of 25 cubic units. The weights, volumes, and values of the three items are given in Table 12.1.
How can the traveler maximize the value of the items? It is straightforward to calculate the solutions using brute force, by iterating over all possible combinations and eliminating those that are overweight or too large to fit.
We define a number of support functions, then run over all possible values of the knapsack contents (after expand.grid()generates the list). The findvalue() function checks the constraints and sets the value to 0 if they are not satisfied, and otherwise calculates them for the set. Theapply() function (see 2.6.4) is used to run a function for each item of a vector.
12.8. CONSTRAINED OPTIMIZATION: THE KNAPSACK PROBLEM 209
> library(lattice)
> xyplot(numFlights ~ date, xlab="", ylab="number of flights on Monday",
> type="l", col="black", lwd=2, data=mondays)
number of flights on Monday
60 70 80 90 100 110
5 0 0 2 0
0 0 2 5
9 9 1 0
9 9 1
Figure 12.10: Number of flights departing Bradley airport on Mondays over time
> # Define constants and useful functions
> weight = c(0.3, 0.2, 2.0)
> volume = c(2.5, 1.5, 0.2)
> value = c(3000, 1800, 2500)
> maxwt = 25
> maxvol = 25
> # minimize the grid points we need to calculate
> max.items = floor(pmin(maxwt/weight, maxvol/volume))
>
Table 12.1: Weights, volume, and values for the knapsack problem Item Weight Volume Value
Panacea 0.3 2.5 3000
Ichor 0.2 1.5 1800
Gold 2.0 0.2 2500
> # useful functions
> getvalue = function(n) sum(n*value)
> getweight = function(n) sum(n*weight)
> getvolume = function(n) sum(n*volume)
>
> # main function: return 0 if constraints not met,
> # otherwise return the value of the contents, and their weight
> findvalue = function(x) {
thisweight = apply(x, 1, getweight) thisvolume = apply(x, 1, getvolume) fits = (thisweight <= maxwt) &
(thisvolume <= maxvol) vals = apply(x, 1, getvalue)
return(data.frame(panacea=x[,1], ichor=x[,2], gold=x[,3], value=fits*vals, weight=thisweight,
volume=thisvolume)) }
>
> # Find and evaluate all possible combinations
> combs = expand.grid(lapply(max.items, function(n) seq.int(0, n)))
> values = findvalue(combs) Now we can display the solutions.
> max(values$value) [1] 54500
> values[values$value==max(values$value),]
panacea ichor gold value weight volume
2067 9 0 11 54500 24.7 24.7
2119 6 5 11 54500 24.8 24.7
2171 3 10 11 54500 24.9 24.7
2223 0 15 11 54500 25.0 24.7
The first solution (with 9 panacea, no ichor, and 11 gold) satisfies the volume constraint, maximizes the value, and also minimizes the weight. More sophisticated approaches are available using thelpSolvepackage for linear/integer problems.
Appendix A
Introduction to R and RStudio
This chapter provides a (brief) introduction to R and RStudio. R is a free, open-source software environment for statistical computing and graphics [77, 130]. RStudio is an open- source integrated developement environment for R that adds many features and produc- tivity tools for R. The chapter includes a short history, installation information, a sample session, background on fundamental structures and actions, information about help and documentation, and other important topics.
R is a general-purpose package that includes support for a wide variety of modern statistical and graphical methods (many of which have been contributed by users). It is available for most UNIX platforms, Windows, and MacOS. The R Foundation for Statistical Computing holds and administers the copyright of R software and documentation. R is available under the terms of the Free Software Foundation’s GNU General Public License in source code form.
RStudio facilitates use of R by integrating R help and documentation, providing a workspace browser and data viewer, and supporting syntax highlighting, code completion, and smart indentation. It integrates reproducible analysis with Sweave, knitr, and R Mark- down (see 11.3), supports the creation of slide presentations, and includes a debugging environment (see 4.1.6). It facilitates the creation of dynamic web applications using Shiny (see 12.6.2). It also provides support for multiple projects as well as an interface to source code control systems such as GitHub. It has become the default interface for many R users, including the authors.
RStudio is available as a client (standalone) for Windows, Mac OS X, and Linux. There is also a server version. Commercial products and support are available in addition to the open-source offerings (seehttp://www.rstudio.com/idefor details).
The first versions of R were written by Ross Ihaka and Robert Gentleman at the Univer- sity of Auckland, New Zealand, while current development is coordinated by the R Develop- ment Core Team, a group of international volunteers. As of October 2014, this group con- sisted of Douglas Bates, John Chambers, Peter Dalgaard, Seth Falcon, Robert Gentleman, Kurt Hornik, Ross Ihaka, Michael Lawrence, Friedrich Leisch, Uwe Ligges, Thomas Lum- ley, Martin Maechler, Martin Morgan, Duncan Murdoch, Paul Murrell, Martyn Plummer, Brian Ripley, Deepayan Sarkar, Duncan Temple Lang, Luke Tierney, and Simon Urbanek.
Former members of the R Core include Heiner Schwarte (through 1999), Guido Masarotto (through 2003), and Stefano Iacus (through 2014). Many hundreds of other people have contributed to the development of R or developed add-on libraries and packages.
R is similar to the S language, a flexible and extensible statistical environment originally developed in the 1980s at AT&T Bell Labs (now Alcatel–Lucent). Insightful Corporation has continued the development of S in their commercial software package S-PLUSTM.
Figure A.1: R Windows graphical user interface
New users are encouraged to download and install R from the Comprehensive R archive network (CRAN, http://www.r-project.org, see A.1) and install RStudio from http:
//www.rstudio.com/ide. The sample session in the appendix of the Introduction to R document, also available from CRAN (see A.2), is highly recommended.